Today, when learning dynamic proxy in spring AOP, we encountered a problem of type conversion java.lang.ClassCastException : com.sun.proxy .$Proxy16 cannot be cast to com.Charon.service .UserServiceImpl
First, introduce the dynamic proxy of spring.
Spring uses two kinds of dynamic proxy: JDK proxy and cglib. Using the former, you must implement at least one interface to intercept methods. Using the latter requires two jar packages: asm.jar and cglib.jar , and modify the spring configuration file.
I used JDK proxy in the test and found the cause of the problem by looking up the data. Here are my test cases:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl)context.getBean("userServiceImpl");
UserService userServiceImpl = (UserService)context.getBean("userServiceImpl");
Reason: the red part is the root of the error. The implementation class of proxy cannot be converted by the implementation class of interface (userserviceimpl). They are the same level and should be converted by the common interface. Modify the red code:
UserService userServiceImpl = (UserService) context.getBean ("userServiceImpl");//UserService01_ AOP is the interface
After modification, the program runs normally.