在使用Spring AOP时,遇到转换错误:

转载自http://www.cnblogs.com/xing901022/p/4264172.html

在使用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" 即可。

  【解释说明】

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

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

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

  

  当然,如果本身不是基于接口的,那么会自动使用cglib的方式,在这里很奇怪为什么没有自动走cglib的方式。

  个中缘由,还得去看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>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值