用AOP攔截自定義註解並獲取註解屬性與上下文引數(基於Springboot框架)
阿新 • • 發佈:2018-12-21
目錄
AOP可以用於日誌的設計,這樣話就少不了要獲取上下文的資訊,博主在設計日誌模組時考慮了一下此法,整理了一下如何用AOP來攔截你自定義的註解。
自定義註解
首先先自定義一個註解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Axin { /** * 所屬模組 * @return */ String module() default "日誌模組"; /** * 動作描述 * @return */ String desc() default "無動作"; }
- @Documented:註解表明製作javadoc時,是否將註解資訊加入文件。如果註解在宣告時使用了@Documented,則在製作javadoc時註解資訊會加入javadoc。
- @Target:用來說明該註解可以被宣告在那些元素之前
- @Target(ElementType.TYPE) //介面、類、列舉、註解
- @Target(ElementType.FIELD) //欄位、列舉的常量
- @Target(ElementType.METHOD) //方法
- @Target(ElementType.PARAMETER) //方法引數
- @Target(ElementType.CONSTRUCTOR) //建構函式
- @Target(ElementType.LOCAL_VARIABLE)//區域性變數
- @Target(ElementType.ANNOTATION_TYPE)//註解
- @Target(ElementType.PACKAGE) ///包
- @Retention:用來說明該註解類的生命週期。
- @Retention(RetentionPolicy.SOURCE) —— 這種型別的Annotations只在原始碼級別保留,編譯時就會被忽略
- @Retention(RetentionPolicy.CLASS) —— 這種型別的Annotations編譯時被保留,在class檔案中存在,但JVM將會忽略
- @Retention(RetentionPolicy.RUNTIME) —— 這種型別的Annotations將被JVM保留,所以他們能在執行時被JVM或其他使用反射機制的程式碼所讀取和使用.
定義切面
/**
* @author Axin
*/
@Aspect
@Component
public class AxinAspect {
/**
* 這裡定義了一個總的匹配規則,以後攔截的時候直接攔截log()方法即可,無須去重複寫execution表示式
*/
@Pointcut("@annotation(Axin)")
public void log() {
}
@Before("log()&&@annotation(axin)")
public void doBefore(JoinPoint joinPoint,Axin axin) {
System.out.println("******攔截前的邏輯******");
System.out.println("目標方法名為:" + joinPoint.getSignature().getName());
System.out.println("目標方法所屬類的簡單類名:" + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("目標方法所屬類的類名:" + joinPoint.getSignature().getDeclaringTypeName());
System.out.println("目標方法宣告型別:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
//獲取傳入目標方法的引數
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
System.out.println("第" + (i + 1) + "個引數為:" + args[i]);
}
System.out.println("被代理的物件:" + joinPoint.getTarget());
System.out.println("代理物件自己:" + joinPoint.getThis());
System.out.println("攔截的註解的引數:");
System.out.println(axin.module());
System.out.println(axin.desc());
}
@Around("log()&&@annotation(axin)")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint,Axin axin) throws Throwable {
System.out.println("環繞通知:");
System.out.println(axin.module());
System.out.println(axin.desc());
Object result = null;
result = proceedingJoinPoint.proceed();
return result;
}
@After("log()")
public void doAfter() {
System.out.println("******攔截後的邏輯******");
}
}
匹配規則:
//匹配AOP物件的目標物件為指定型別的方法,即DemoDao的aop的代理物件
@Pointcut("this(com.hhu.DemaoDao)")
public void thisDemo() {
...
}
通知類別:
- 前置通知(Before advice)- 在目標方便呼叫前執行通知
- 後置通知(After advice)- 在目標方法完成後執行通知
- 返回通知(After returning advice)- 在目標方法執行成功後,呼叫通知
- 異常通知(After throwing advice)- 在目標方法丟擲異常後,執行通知
- 環繞通知(Around advice)- 在目標方法呼叫前後均可執行自定義邏輯
獲取上下文資訊JoinPoint
JoinPoint物件封裝了SpringAop中切面方法的資訊,在切面方法中新增JoinPoint引數,就可以獲取到封裝了該方法資訊的JoinPoint物件. 注意:這用於非環繞通知
方法名 | 功能 |
---|---|
Signature getSignature(); | 獲取封裝了署名資訊的物件,在該物件中可以獲取到目標方法名,所屬類的Class等資訊 |
Object[] getArgs(); | 獲取傳入目標方法的引數物件 |
Object getTarget(); | 獲取被代理的物件 |
Object getThis(); | 獲取代理物件 |
方法使用模板:
public void doBefore(JoinPoint joinPoint) {
System.out.println("******攔截前的邏輯******");
System.out.println("目標方法名為:" + joinPoint.getSignature().getName());
System.out.println("目標方法所屬類的簡單類名:" + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("目標方法所屬類的類名:" + joinPoint.getSignature().getDeclaringTypeName());
System.out.println("目標方法宣告型別:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
//獲取傳入目標方法的引數
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
System.out.println("第" + (i + 1) + "個引數為:" + args[i]);
}
System.out.println("被代理的物件:" + joinPoint.getTarget());
System.out.println("代理物件自己:" + joinPoint.getThis());
}
ProceedingJoinPoint
ProceedingJoinPoint物件是JoinPoint的子介面,該物件只用在@Around的切面方法中
方法名 | 功能 |
---|---|
Object proceed() throws Throwable | 執行目標方法 |
Object proceed(Object[] var1) throws Throwable | 傳入的新的引數去執行目標方法 |
定義測試方法
//Service介面
public interface AxinService {
String axinRun(String arg1, User user);
}
//實現類
/**
* @author Axin
*/
@Component
public class AxinServiceImpl implements AxinService {
@Axin(module = "print",desc = "列印")
@Override
public String axinRun(String arg1, User user) {
String res = arg1 + user.getName() + user.getAge();
return res;
}
public String axinRun(String arg1, Person person) {
String res = arg1 + person.getName() + person.getAge();
return res;
}
}
//控制類
/**
* @author Axin
*/
@RestController
public class HelloController {
@Autowired
AxinService axinService;
@RequestMapping("/hello")
public String hello() {
User user = new User();
user.setAge(10);
user.setName("張三");
String res = axinService.axinRun("Test:", user);
return "Hello Spring Boot!<br>"+res;
}
}
測試結果
環繞通知:
print
列印
******攔截前的邏輯******
目標方法名為:axinRun
目標方法所屬類的簡單類名:AxinService
目標方法所屬類的類名:com.axin.springboot.service.AxinService
目標方法宣告型別:public abstract
第1個引數為:Test:
第2個引數為:User(id=null, name=張三, age=10, date=null)
被代理的物件:[email protected]
代理物件自己:[email protected]
攔截的註解的引數:
print
列印
******攔截後的邏輯******
小結
通過上述的程式碼演示,我們可以自定義一個註解,然後配置切面來攔截有註解的方法,同時也可以獲得方法傳入的引數來完成你的業務需求。