Spring AOP的proxy-target-class详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_22078107/article/details/85882211

proxy-target-class

该属性值默认false,表示使用JDK动态代理织入增强;当值为true时,表示使用CGLib动态代理织入增强;但是,即使设置为false,如果目标类没有生命接口,则Spring将自动使用CGLib动态代理.

proxy-target-class属性值决定是基于接口的还是基于类的代理被创建

  1. true则是基于类的代理将起作用(需要cglib库),
  2. false或者省略这个属性,则标准的JDK 基于接口的代理将起作用。


proxy-target-class在spring事务、aop、缓存这几块都有设置,其作用都是一样的。

  • <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
  • <aop:config proxy-target-class="true">
  • <cache:annotation-driven proxy-target-class="true"/>

或者单独这样写也可以:

<aop:aspectj-autoproxy proxy-target-class="true"/> 

通俗理解:

当要使用实现了某个接口的类让Spring来生成bean时,无需在aop配置中添加proxy-target-class,因为它默认为false.

但如果要使用一个指定的类,让Spring来生成bean,并使用它的某个方法时,需要在aop配置上加上一句proxy-target-class="true",否则运行时,会出现:

java.lang.ClassCastException: com.sun.proxy.$Proxy2 cannot be cast to com.Imp.userImp

类似的错误.

    public void test() {  
        ApplicationContext ctx = new ClassPathXmlApplicationContext(  
                "applicationContext.xml");  
        //下面注释的两行,proxy-target-class="false"  
        //IDAO daoImp = (IDAO) ctx.getBean("DAOImp");  
        //daoImp.add();  
  
        //以下两行,proxy-target-class="true"  
        DAOImp2 daoImp2 = (DAOImp2) ctx.getBean("DAOImp2");  
        daoImp2.add2();  
    }  

猜你喜欢

转载自blog.csdn.net/qq_22078107/article/details/85882211