Resolving Spring using dynamic agents

Source: Internet
Author: User

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
    • 3193

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.