because it is a JDK dynamic proxy that implements问题 看这一篇就够了


一、背景

开发中常见这个错误:

The bean 'xxxService' could not be injected as a'com.xxxx.xxx.xxxService' because it is a JDK dynamic proxy that implements:
xxxxxx
Action:
Consider injecting the bean as one of its interfaces orforcing the use of CGLib-based proxiesby setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.

 

二、常见解决方案


主要配置基于JDK的代理还是基于类的动态代理的配置,这种错误提示需要设置基于类的代理才行。

比如单元测试里注入了实现类,且实现类里有@Transaction注解

 

如果是springboot项目,在配置里设置

spring.aop.proxy-target-class=true
proxy-target-class属性值决定是基于JDK接口还是基于类的代理被创建。

如果为true代表基于类的代理,

如果为false代表基于JDK接口的代理。

或者在配置类上设置

@EnableAspectJAutoProxy(proxyTargetClass = true)
当然另外的几个注解都支持

@EnableAsync

 

 

@EnableCaching

或者

@EnableTransactionManagement (proxyTargetClass = true)
都可以设置proxyTargetClass = true属性

根据自己的情况选择,

@EnableAspectJAutoProxy单纯设置基于类的动态代理,其他的都是开启异步,开启缓存,开启事务管理等注解顺便开启基于类的动态代理。

 

三、其他问题引起

 

3.1 另外多半是使用@Resource注解导致的问题

因为@Autowired默认按类型装配,而 @Resource优先按名称装配,如果使用

@Resource
private XabYcdService ycdSerivce;
恰巧有另外一个bean叫“ycdSerivce” 也可能出现这个错误。

3.2  粗心导致

比如基于xml的配置

<bean id="xabYcdService" class="com.xxx.xxx.xxx.xxMabYcdService"/>
这里的class并不是实际应该配置的:com.xxx.xxx.xxx.xxXabYcdService 


原文链接:https://blog.csdn.net/w605283073/article/details/90454057


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM