首页 > 技术文章 > 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

pjhaymy 2020-10-02 19:02 原文

今天在使用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);

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

在这里插入图片描述

推荐阅读