Exception in thread “main“ java.lang.ClassCastException: com.sun.proxy.$Proxy8 cannot be cast to XXX

今天在使用spring框架来写一个事务织入的时候出现了如下报错
注意出现如下两个错误都可能是因为没有正确配置proxy-target-class的值导致的:
错误一:No qualifying bean of type ‘com.pjh.service.Imp.serviceImp’ available
错误二: Exception in thread “main” java.lang.ClassCastException: com.sun.proxy.$Proxy8 cannot be cast to XXX-------动态代理(proxy-target-class属性的意义)

这句话的意思大致为:没有类型为’com.pjh.service.Imp.serviceImp”合格的bean可用

为什么?

查阅资料得:这是由于没有配置proxy-target-class导致的
proxy-target-class有两个值:true/false
决定是基于接口的还是基于的代理被创建。
如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。
如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理将起作用。

我使用这段代码来获取:
声明:serviceImp是实现service接口的父类
serviceImp bean1 =(serviceImp) classPathXmlApplicationContext.getBean(serviceImp.class);
而serviceImp是一个类而不是一个接口
而我在进行织入的时候没有配置proxy-target-class属性,默认就为proxy-target-class=false,这是基于接口的代理所以报错了
也就是报错的内容 :没有类型为’com.pjh.service.Imp.serviceImp”合格的bean可用

 <aop:config>
      <aop:pointcut id="txPointcut" expression="execution(* com.pjh.service.Imp.serviceImp.*(..))"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
  </aop:config>

解决方案

解决方法一:
当我将代码的proxy-target-class的值改为true的时候就不会报错了,即改为基于类的代理

<aop:config proxy-target-class="true">
      <aop:pointcut id="txPointcut" expression="execution(* com.pjh.service.Imp.serviceImp.*(..))"/>
      <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
  </aop:config>

解决方法二
将传入的参数改为接口,则无需添加proxy-target-class,因为默认就是false,就是基于接口代理
声明:serivce是serviceImp的父类是一个接口

 service bean1 =(service) classPathXmlApplicationContext.getBean(service.class);

以上就是今天遇到的错误及其解决方案,如有帮助还请点赞关注,这是对博主的最大支持,我会经常更新我学习的笔记及遇到的问题

在这里插入图片描述

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值