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

在使用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>
复制代码

 

posted @   xingoo  阅读(31246)  评论(4编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示