Several common exceptions during Spring development (3): java. lang. classCastException: com. sun. proxy. $ Proxy4 cannot be cast to com.edu. aop. arithmeticCalculatorImpl at com.edu. aop. main. main (Main. java: 11 ),
This exception was encountered during Spring case development.
Paste the complete exception information:
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy4 cannot be cast to com.edu.aop.ArithmeticCalculatorImpl at com.edu.aop.Main.main(Main.java:11)
Cause: Spring AOP is a technology that implements AOP and is implemented using the "dynamic proxy technology.
The interface is used in this case. In this example, the editor defines an interface ArithmeticCalculator, and then implements this interface using the entity class ArithmeticCalculatorImpl.
Locate the error code (the second sentence of the Code is posted here ):
ApplicationContext act=new ClassPathXmlApplicationContext("applicationContext.xml");ArithmeticCalculatorImpl arithmetic=(ArithmeticCalculatorImpl)act.getBean("arithmetic");
Paste the configuration information in the configuration file:
<! -- Configure bean --> <bean id = "arithmetic" class = "com.edu. aop. ArithmeticCalculatorImpl"> </bean>
We can see that the configured bean is the implementation class of the interface, so the String AOP technology performs dynamic proxy on it, and the result object of the proxy is the same as the implementation class of this interface. That is to say, the proxy object and the interface implementation class defined by the mini-Editor implement this interface respectively. The conversion between the two is not allowed according to the conversion principle of the java language, so a conversion exception is thrown.
This exception can be solved when the conversion type is changed to the interface type. Change the red code part:
ArithmeticCalculator arithmetic=(ArithmeticCalculator)act.getBean("arithmetic");
Refer to blog:
Http://blog.csdn.net/yinzn2011/article/details/46455973
Http://blog.csdn.net/a1491918446/article/details/48715247