Spring aop报错:com.sun.proxy.$Proxyxxx cannot be cast to yyy

在使用Spring AOP时,遇到以下的错误:java

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)spring

  看报错信息,显示的是动态代理生成的类没法转换到咱们自定义的实现类。app

  解决办法:

  在aop:config标签中添加 proxy-target-class="true" 便可。spa

 

  【解释说明】.net

  按照博客的说法:http://blog.csdn.net/z69183787/article/details/17161297代理

  因为生成代理类有两种方式:JDK和CGLIB,一种是基于接口的,一种是基于类的。code

  若是添加上面的属性则使用基于类的cglib的方式,相反,若是没有写或者是false则经过jdk的基于接口的方式生成代理类。orm

  

  固然,若是自己不是基于接口的,那么会自动使用cglib的方式,在这里很奇怪为何没有自动走cglib的方式。blog

  个中原因,还得去看aop的源码,这里先作下记录。接口

 

  下面是我本身的spring配置文件,仅供参考

<aop:config proxy-target-class="true">
        <aop:aspect ref="audience">
            <aop:before pointcut="execution(* com.spring.test.action1.Performer.perform(..))" method="takeSeats"/>
            <aop:before pointcut="execution(* com.spring.test.action1.Performer.perform(..))" method="turnOffCellPhones"/>
            <aop:after-returning pointcut="execution(* com.spring.test.action1.Performer.perform(..))" method="applaud"/>
            <aop:after-throwing pointcut="execution(* com.spring.test.action1.Performer.perform(..))" method="demandRefund"/>
        </aop:aspect>
    </aop:config>
相关文章
相关标签/搜索