在使用Spring AOP时,遇到如下的错误:
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to com.spring.test.setter.Instrumentalist
at com.spring.test.setter.test.main(test.java:12)
解决办法:在aop:config标签中添加 proxy-target-class="true" 即可。
<aop:config proxy-target-class="true">
</aop:config>
原因从网上找的如下:
对于Spring AOP 采用两种代理方法,一种是常规JDK,一种是CGLI,当代理对象实现了至少一个接口时,默认使用JDK动态创建代理对象,当代理对象没有实现任何接口时,就会使用CGLIB方法。
proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理理将起作用。