Resolves an issue in which Spring uses dynamic proxy type conversions to fail--java.lang.classcastexception:com.sun.proxy. $Proxy $ cannot is cast to ...reprinted June 11, 2015 12:32:40
- Label:
- Solutions/
- Spring/
- AOP/
- Proxy
Today, when learning about dynamic proxies in spring AOP, a type conversion problem was encountered: Java.lang.ClassCastException:com.sun.proxy. $Proxy 8 cannot be cast to Com.bjsxt.service.UserServiceImpl01_AOP.
Let's start with spring's dynamic agent.
There are two types of dynamic agents that Spring uses: JDK Proxy and Cglib. The use of the former must implement at least one interface to achieve the interception of the method. Using the latter requires two jar packages: Asm.jar and Cglib.jar, and modifies the spring configuration file.
I used the JDK Proxy during the test and found the cause of the problem after finding the data. Here is my test case:
ApplicationContext ac = new Classpathxmlapplicationcontext ("./com/bjsxt/springconfig/annotation_01_aop.xml");
USERSERVICEIMPL01_AOP UserService = (USERSERVICEIMPL01_AOP) ac.getbean ("Userserviceimpl01_aop");
Userservice.method3 ();
Cause: The red part is the source of the error. You cannot use the implementation class (USERSERVICEIMPL01_AOP) of an interface to transform the implementation class of a proxy, which are peers and should be converted with a common interface. Modify the Red code:
USERSERVICE01_AOP UserService = (USERSERVICE01_AOP) ac.getbean ("Userserviceimpl01_aop");//userservice01_aop is an interface
After the modification, the program runs normally.
The reader can understand how the JDK proxy works, and it is easy to understand why the error occurred.
Resolving Spring using dynamic agents