解决: org.springframework.beans.factory.BeanNotOfRequiredTypeException办法

来源:互联网 发布:天干地支的简便算法 编辑:程序博客网 时间:2024/04/28 20:03

 错误信息:

    org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'aisleService' must be of type [com.gdie.whlocation.service.impl.AisleService], but was actually of type [$Proxy38]

 

    这个问题出现的原因:一般在使用annotation的方式注入spring的bean 出现的,具体是由于spring采用代理的机制导致的,看使用的代码:

 

 

Java代码  收藏代码
  1. 1. 使用类注入:  
  2. @Resource(name = "aisleService")  
  3. private AisleService aisleService;  
  4.   
  5. 2. 使用接口注入:  
  6. @Resource(name = "aisleService")  
  7. private IAisleService aisleService;  
 

 

 

代码1不能使用JDK的动态代理注入,原因是jdk的动态代理不支持类注入,只支持接口方式注入;

代码2可以使用jdk动态代理注入;

如果要使用代码1的方式,必须使用cglib代理;

当然了推荐使用代码2的方式,基于接口编程的方式!

 

关于spring动态代理的配置:

 

 

Xml代码  收藏代码
  1. 1.使用aop配置:   
  2.     <aop:config proxy-target-class="false"> </aop:config>   
  3.   
  4. 2. aspectj配置:   
  5.     <aop:aspectj-autoproxy proxy-target-class="true"/>  
  6.       
  7. 3. 事务annotation配置:   
  8.     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>  
 

 

 

3种配置,只要使用一种即可,设置proxy-target-class为true即使用cglib的方式代理对象。

 

 附:spring的aop代理判断逻辑:

 

 

Java代码  收藏代码
  1. //org.springframework.aop.framework.DefaultAopProxyFactory     
  2.   
  3. //参数AdvisedSupport 是Spring AOP配置相关类     
  4.   
  5. public AopProxy createAopProxy(AdvisedSupport advisedSupport)     
  6.   
  7.         throws AopConfigException {     
  8.   
  9.     //在此判断使用JDK动态代理还是CGLIB代理     
  10.   
  11.     if (advisedSupport.isOptimize() || advisedSupport.isProxyTargetClass()     
  12.   
  13.             || hasNoUserSuppliedProxyInterfaces(advisedSupport)) {     
  14.   
  15.         if (!cglibAvailable) {     
  16.   
  17.             throw new AopConfigException(     
  18.   
  19.                     "Cannot proxy target class because CGLIB2 is not available. "    
  20.   
  21.                             + "Add CGLIB to the class path or specify proxy interfaces.");     
  22.   
  23.         }     
  24.   
  25.         return CglibProxyFactory.createCglibProxy(advisedSupport);     
  26.   
  27.     } else {     
  28.   
  29.         return new JdkDynamicAopProxy(advisedSupport);     
  30.   
  31.     }     
  32.   
  33. }  
原创粉丝点击