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

本文探讨了Spring中动态代理的原理与应用,包括不同注入方式的问题与解决方案,重点介绍了如何选择合适的代理策略来实现类与接口之间的灵活绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 错误信息:

    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采用代理的机制导致的,看使用的代码:

 

 

1. 使用类注入:
@Resource(name = "aisleService")
private AisleService aisleService;

2. 使用接口注入:
@Resource(name = "aisleService")
private IAisleService aisleService;
 

 

 

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

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

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

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

 

关于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);   

	}   

}
 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值