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

