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