Spring AOP的proxy-target-class详解
proxy-target-class
该属性值默认为false,表示使用JDK动态代理织入增强;当值为true时,表示使用CGLib动态代理织入增强;但是,即使设置为false,如果目标类没有生命接口,则Spring将自动使用CGLib动态代理.
proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。
- 为true则是基于类的代理将起作用(需要cglib库),
- 为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(); }
上一篇:
多线程四大经典案例