因Spring AOP導(dǎo)致@Autowired依賴注入失敗的解決方法
發(fā)現(xiàn)問題:
之前用springAOP做了個操作日志記錄,這次在往其他類上使用的時候,service一直注入失敗,找了網(wǎng)上好多內(nèi)容,發(fā)現(xiàn)大家都有類似的情況出現(xiàn),但是又和自己的情況不太符合。后來總結(jié)自己的情況發(fā)現(xiàn):方法為private修飾的,在AOP適配的時候會導(dǎo)致service注入失敗,并且同一個service在其他的public方法中就沒有這種情況,十分詭異。
解決過程:
結(jié)合查閱的資料進(jìn)行了分析:在org.springframework.aop.support.AopUtils中:
public static boolean canApply(Pointcut pc, Class targetClass, boolean hasIntroductions) {
if (!pc.getClassFilter().matches(targetClass)) {
return false;
}
MethodMatcher methodMatcher = pc.getMethodMatcher();
IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
}
Set classes = new HashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
classes.add(targetClass);
for (Iterator it = classes.iterator(); it.hasNext();) {
Class clazz = (Class) it.next();
Method[] methods = clazz.getMethods();
for (int j = 0; j < methods.length; j++) {
if ((introductionAwareMethodMatcher != null &&
introductionAwareMethodMatcher.matches(methods[j], targetClass, hasIntroductions)) ||
methodMatcher.matches(methods[j], targetClass)) {
return true;
}
}
}
return false;
}
此處Method[] methods = clazz.getMethods();只能拿到public方法。
execution(* *(..)) 可以匹配public/protected的,因?yàn)閜ublic的有匹配的了,目標(biāo)類就代理了,,,再進(jìn)行切入點(diǎn)匹配時也是能匹配的,而且cglib方式能拿到包級別/protected方法,而且包級別/protected方法可以直接通過反射調(diào)用。
private 修飾符的切入點(diǎn) 無法匹配 Method[] methods = clazz.getMethods(); 這里的任何一個,因此無法代理的。 所以可能因?yàn)閜rivate方法無法被代理,導(dǎo)致@Autowired不能被注入。
修正辦法:
1、將方法修飾符改為public;
2、使用AspectJ來進(jìn)行注入。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
IntelliJ IDEA2020.1版本更新pom文件自動導(dǎo)包的方法
這篇文章主要介紹了IntelliJ IDEA2020.1版本更新pom文件自動導(dǎo)包的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
使用SpringBoot動態(tài)切換數(shù)據(jù)源的實(shí)現(xiàn)方式
在我們企業(yè)項(xiàng)目開發(fā)的過程中,有的時候,一個項(xiàng)目需要在運(yùn)行時,根據(jù)某種條件選擇使用哪個數(shù)據(jù)源,那么此時該怎么進(jìn)行動態(tài)切換呢,本文給大家例舉一種常見的實(shí)現(xiàn)方式,文中有詳細(xì)的實(shí)現(xiàn)步驟,需要的朋友可以參考下2023-12-12
java web開發(fā)中獲取tomcat上properties文件內(nèi)容的方法
java web開發(fā)中如何獲取tomcat上properties文件內(nèi)容的方法,方便文件存儲位置的修改,解耦和,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
詳解Java對象序列化為什么要使用SerialversionUID
這篇文章主要介紹了詳解Java對象序列化為什么要使用SerialversionUID,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
SpringMVC中Model與Session的區(qū)別說明
這篇文章主要介紹了SpringMVC中Model與Session的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
使用Mybatis-Plus時的SqlSessionFactory問題及處理
這篇文章主要介紹了使用Mybatis-Plus時的SqlSessionFactory問題及處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
Mybatis中使用updateBatch進(jìn)行批量更新
這篇文章主要介紹了Mybatis中使用updateBatch進(jìn)行批量更新的相關(guān)資料,有逐條更新,sql批量更新等,具體實(shí)例代碼大家參考下本文2018-04-04

