因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的,因為public的有匹配的了,目標(biāo)類就代理了,,,再進(jìn)行切入點匹配時也是能匹配的,而且cglib方式能拿到包級別/protected方法,而且包級別/protected方法可以直接通過反射調(diào)用。
private 修飾符的切入點 無法匹配 Method[] methods = clazz.getMethods(); 這里的任何一個,因此無法代理的。 所以可能因為private方法無法被代理,導(dǎo)致@Autowired不能被注入。
修正辦法:
1、將方法修飾符改為public;
2、使用AspectJ來進(jìn)行注入。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
mybatis/mybatis-plus模糊查詢語句特殊字符轉(zhuǎn)義攔截器的實現(xiàn)
在開發(fā)中,我們通常會遇到這樣的情況。用戶在錄入信息是錄入了‘%’,而在查詢時無法精確匹配‘%’。究其原因,‘%’是MySQL的關(guān)鍵字,如果我們想要精確匹配‘%’,那么需要對其進(jìn)行轉(zhuǎn)義,本文就詳細(xì)的介紹一下2021-11-11
Java數(shù)據(jù)結(jié)構(gòu)之加權(quán)無向圖的設(shè)計實現(xiàn)
加權(quán)無向圖是一種為每條邊關(guān)聯(lián)一個權(quán)重值或是成本的圖模型。這種圖能夠自然地表示許多應(yīng)用。這篇文章主要介紹了加權(quán)無向圖的設(shè)計與實現(xiàn),感興趣的可以了解一下2022-11-11
SpringBoot實現(xiàn)上傳文件到AWS S3的代碼
這篇文章主要介紹了SpringBoot實現(xiàn)上傳文件到AWS S3的代碼,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2020-10-10
使用maven整合Spring+SpringMVC+Mybatis框架詳細(xì)步驟(圖文)
這篇文章主要介紹了使用maven整合Spring+SpringMVC+Mybatis框架詳細(xì)步驟(圖文),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05

