Spring aop失效的幾種解決方案
先看下這個(gè)問題的背景:假設(shè)有一個(gè)spring應(yīng)用,開發(fā)人員希望自定義一個(gè)注解@Log,可以加到指定的方法上,實(shí)現(xiàn)自動(dòng)記錄日志(入?yún)?、出參、響?yīng)耗時(shí)這些)
package com.cnblogs.yjmyzz.springbootdemo.aspect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Log {
}
然后再寫一個(gè)Aspect來解析這個(gè)注解,對打了Log注解的方法進(jìn)行增強(qiáng)處理
package com.cnblogs.yjmyzz.springbootdemo.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Component
@Aspect
public class LogAspect {
@Pointcut("execution (* com.cnblogs.yjmyzz.springbootdemo.service..*.*(..))")
public void logPointcut() {
}
@Around("logPointcut()")
public void around(JoinPoint point) {
String methodName = point.getSignature().getName();
Object[] args = point.getArgs();
Class<?>[] argTypes = new Class[point.getArgs().length];
for (int i = 0; i < args.length; i++) {
argTypes[i] = args[i].getClass();
}
Method method = null;
try {
method = point.getTarget().getClass().getMethod(methodName, argTypes);
} catch (Exception e) {
e.printStackTrace();
}
//獲取方法上的注解
Log log = method.getAnnotation(Log.class);
if (log != null) {
//演示方法執(zhí)行前,記錄一行日志
System.out.println("before:" + methodName);
}
try {
//執(zhí)行方法
((ProceedingJoinPoint) point).proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
if (log != null) {
//演示方法執(zhí)行后,記錄一行日志
System.out.println("after:" + methodName);
}
}
}
}
寫一個(gè)測試Service類:
package com.cnblogs.yjmyzz.springbootdemo.service;
import com.cnblogs.yjmyzz.springbootdemo.aspect.Log;
import org.springframework.stereotype.Component;
@Component
public class HelloService {
@Log
public void sayHi(String msg) {
System.out.println("\tsayHi:" + msg);
}
public void anotherSayHi(String msg) {
this.sayHi(msg);
}
}
最后來跑一把:
package com.cnblogs.yjmyzz.springbootdemo;
import com.cnblogs.yjmyzz.springbootdemo.service.HelloService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* @author 菩提樹下的楊過
*/
@ComponentScan("com.cnblogs.yjmyzz")
@Configuration
@EnableAspectJAutoProxy
public class SampleApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleApplication.class);
HelloService helloService = context.getBean(HelloService.class);
helloService.sayHi("hi-1");
System.out.println("\n");
helloService.anotherSayHi("hi-2");
}
}
輸出如下:

顯然HelloService中的anotherSayHi方法,并未被aop增強(qiáng)。 原因其實(shí)很簡單,了解AOP原理的同學(xué)想必都知道,AOP的實(shí)現(xiàn)有二類,如果是基于接口的,會(huì)采用動(dòng)態(tài)代理,生成一個(gè)代理類,如果是基于類的,會(huì)采用CGLib生成子類,然后在子類中擴(kuò)展父類中的方法。

本文中HelloService并不是一個(gè)接口,所以從上圖的斷點(diǎn)中可以看出,當(dāng)Spring運(yùn)行時(shí),HelloService被增加為...EnhancerBySpringCGLib...。但是當(dāng)調(diào)用到anotherSayHi時(shí)

方法的調(diào)用方,其實(shí)是原始的HelloSerfvice實(shí)例,即:是未經(jīng)過Spring AOP增強(qiáng)的對象實(shí)例。所以解決問題的思路就有了,想辦法用增強(qiáng)后的HelloService實(shí)例來調(diào)用!
方法一:用Autowired 注入自身的實(shí)例

這個(gè)方法,第一眼看上去感覺有些怪,自己注入自己,感覺有點(diǎn)象遞歸/死循環(huán)的搞法,但確實(shí)可以work,Spring在解決循環(huán)依賴上有自己的處理方式,避免了死循環(huán)。
方法二:從Spring上下文獲取增強(qiáng)后的實(shí)例引用

原理與方法一其實(shí)類似,不多解釋。
方法三: 利用AopContext

不過這個(gè)方法要注意的是,主類入口上,必須加上exporseProxy=true,參考下圖:

最后來驗(yàn)證下這3種方法是否生效:

從運(yùn)行結(jié)果上看,3種方法都可以解決這個(gè)問題?!?/p>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
IDEA類與方法注釋模板設(shè)置圖文教程(非常詳細(xì))
IDEA自帶的注釋模板不是太好用,我本人到網(wǎng)上搜集了很多資料系統(tǒng)的整理了一下制作了一份比較完整的模板來分享給大家,下面這篇文章主要給大家介紹了關(guān)于IDEA類與方法注釋模板設(shè)置的相關(guān)資料,需要的朋友可以參考下2022-09-09
解決RabbitMq消息隊(duì)列Qos?Prefetch消息堵塞問題
這篇文章主要為大家介紹了關(guān)于如何解決解決RabbitMq?Qos?Prefetch消息堵塞的問題分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-01-01
SpringBoot?Security從入門到實(shí)戰(zhàn)示例教程
Spring?Security是一個(gè)功能強(qiáng)大且高度可定制的身份驗(yàn)證和訪問控制框架,接下來通過本文給大家介紹SpringBoot?Security從入門到實(shí)戰(zhàn)示例教程,感興趣的朋友一起看看吧2022-05-05
Java實(shí)現(xiàn)重定向過程中添加請求頭信息
在Java中,我們經(jīng)常需要使用網(wǎng)絡(luò)請求來與服務(wù)器進(jìn)行通信,在進(jìn)行網(wǎng)絡(luò)請求時(shí),有時(shí)我們需要在重定向過程中添加請求頭信息,本文將介紹如何使用Java在重定向過程中添加請求頭,并提供相應(yīng)的代碼示例,2023-10-10
Java實(shí)現(xiàn)FTP批量大文件上傳下載篇1
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)FTP批量大文件上傳下載的基礎(chǔ)篇,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08

