java中BeanNotOfRequiredTypeException的问题解决(@Autowired和@Resource注解的不同)
作者:自知自省
本文主要介绍了java中BeanNotOfRequiredTypeException的问题解决(@Autowired和@Resource注解的不同),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
1. 错误信息
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named ‘aisleService’ must be of type [com.gdie.whlocation.service.impl.AisleService], but was actually of type [$Proxy38]
2. 问题原因
一般在使用annotation的方式注入spring的bean 出现的,具体是由于spring采用代理的机制导致的,看使用的代码:
3. @Autowired和@Resource注解的区别
1. 使用类注入:
@Resource(name = "aisleService") private AisleService aisleService;
2. 使用接口注入:
@Resource(name = "aisleService") private IAisleService aisleService;
代码1不能使用JDK的动态代理注入,原因是JDK的动态代理不支持类注入,只支持接口方式注入;
代码2可以使用JDK动态代理注入;
如果要使用代码1的方式,必须使用cglib代理;当然了推荐使用代码2的方式,基于接口编程的方式!
使用1的方式也是可以的,建议试一下@Autowired这个注解:
- @Autowired这个注解和@Resource注解不同的是方法类型不同;
- @Autowired是按类的类型注入的 ,是不用区分注入名字的;
- @Resource是按照类的名字注入的,区分注入名字的大小写的写错了也会报BeanNotOfRequiredTypeException异常;
4. 关于spring动态代理的配置:
1.使用aop配置:
<aop:config proxy-target-class="false"> </aop:config>
2. aspectj配置:
<aop:aspectj-autoproxy proxy-target-class="true"/>
3. 事务annotation配置:
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
3种配置,只要使用一种即可,设置proxy-target-class为true即使用cglib的方式代理对象。
附:spring的aop代理判断逻辑:
//org.springframework.aop.framework.DefaultAopProxyFactory //参数AdvisedSupport 是Spring AOP配置相关类 public AopProxy createAopProxy(AdvisedSupport advisedSupport) throws AopConfigException { //在此判断使用JDK动态代理还是CGLIB代理 if (advisedSupport.isOptimize() || advisedSupport.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(advisedSupport)) { if (!cglibAvailable) { throw new AopConfigException( "Cannot proxy target class because CGLIB2 is not available. " + "Add CGLIB to the class path or specify proxy interfaces."); } return CglibProxyFactory.createCglibProxy(advisedSupport); } else { return new JdkDynamicAopProxy(advisedSupport); } }
到此这篇关于java中BeanNotOfRequiredTypeException的问题解决(@Autowired和@Resource注解的不同)的文章就介绍到这了,更多相关java BeanNotOfRequiredTypeException内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!