SpringAOP如何獲取方法參數(shù)上的注解
SpringAOP獲取方法參數(shù)上的注解
一、示例
① 如下代碼,自定義一個(gè)參數(shù)注解@Test,并將其使用到方法參數(shù)上,用于標(biāo)注需要檢驗(yàn)的參數(shù)
/**
* 自定義注解,用于參數(shù)
*/
@Target(PARAMETER)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Test{
}
/**
* 接口層,使用使用@Test注解標(biāo)記參數(shù)
*/
@RestController
@RequestMapping("/v1/test")
public class TestController {
@PostMapping(value = "/email", produces = "application/json")
public String send(@RequestBody @Test MailSendDTO mailSendDTO) {
//TODO 業(yè)務(wù)處理
return "SUCCESS";
}
}
② 通過(guò)切面攔截該方法,從連接點(diǎn)獲取signature,并將signature強(qiáng)轉(zhuǎn)為MethodSignature,從而從MethodSignature對(duì)象可以獲取攔截的方法對(duì)象以及方法參數(shù)注解
@Aspect
@Configuration
public class ValidateAop {
/**
* 切點(diǎn)配置,表達(dá)式, 在com.laoxi.test.controller包下,所有的類public的任意參數(shù)的方法
*/
@Pointcut("execution(public * com.laoxi.test.controller.*.*(..))")
public void validate(){}
@Before("validate()")
public void doBefore(JoinPoint joinPoint){
Object[] params = joinPoint.getArgs();
if(params.length == 0){
return;
}
//獲取方法,此處可將signature強(qiáng)轉(zhuǎn)為MethodSignature
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
//參數(shù)注解,1維是參數(shù),2維是注解
Annotation[][] annotations = method.getParameterAnnotations();
for (int i = 0; i < annotations.length; i++) {
Object param = params[i];
Annotation[] paramAnn = annotations[i];
//參數(shù)為空,直接下一個(gè)參數(shù)
if(param == null || paramAnn.length == 0){
continue;
}
for (Annotation annotation : paramAnn) {
//這里判斷當(dāng)前注解是否為Test.class
if(annotation.annotationType().equals(Test.class)){
//校驗(yàn)該參數(shù),驗(yàn)證一次退出該注解
//TODO 校驗(yàn)參數(shù)
break;
}
}
}
}
}
二、debug
通過(guò)debug代碼:
可發(fā)現(xiàn)連接點(diǎn)實(shí)際為MethodInvocationProceedingJoinPoint對(duì)象,連接點(diǎn)中的signature則為MethodSignatureImpl對(duì)象,是MethodInvocationProceedingJoinPoint的內(nèi)部類。

三、類圖及源碼
MethodInvocationProceedingJoinPoint類圖,頂級(jí)實(shí)現(xiàn)了JoinPoint(以后再使用切面的時(shí)候,可以看看其他類里面都擴(kuò)展了哪些方法可以直接使用)

MethodSignatureImpl類圖,頂級(jí)實(shí)現(xiàn)了Signature(以后再使用切面的時(shí)候,可以看看其他類里面都擴(kuò)展了哪些方法可以直接使用)

用AOP攔截自定義注解并獲取注解屬性與上下文參數(shù)(基于Springboot框架)
AOP可以用于日志的設(shè)計(jì),這樣話就少不了要獲取上下文的信息,博主在設(shè)計(jì)日志模塊時(shí)考慮了一下此法,整理了一下如何用AOP來(lái)攔截你自定義的注解。
自定義注解
首先先自定義一個(gè)注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Axin {
/**
* 所屬模塊
* @return
*/
String module() default "日志模塊";
/**
* 動(dòng)作描述
* @return
*/
String desc() default "無(wú)動(dòng)作";
}
@Documented:注解表明制作javadoc時(shí),是否將注解信息加入文檔。如果注解在聲明時(shí)使用了@Documented,則在制作javadoc時(shí)注解信息會(huì)加入javadoc。
@Target:用來(lái)說(shuō)明該注解可以被聲明在那些元素之前
- @Target(ElementType.TYPE) //接口、類、枚舉、注解
- @Target(ElementType.FIELD) //字段、枚舉的常量
- @Target(ElementType.METHOD) //方法
- @Target(ElementType.PARAMETER) //方法參數(shù)
- @Target(ElementType.CONSTRUCTOR) //構(gòu)造函數(shù)
- @Target(ElementType.LOCAL_VARIABLE)//局部變量
- @Target(ElementType.ANNOTATION_TYPE)//注解
- @Target(ElementType.PACKAGE) ///包
@Retention:用來(lái)說(shuō)明該注解類的生命周期。
- @Retention(RetentionPolicy.SOURCE) —— 這種類型的Annotations只在源代碼級(jí)別保留,編譯時(shí)就會(huì)被忽略
- @Retention(RetentionPolicy.CLASS) —— 這種類型的Annotations編譯時(shí)被保留,在class文件中存在,但JVM將會(huì)忽略
- @Retention(RetentionPolicy.RUNTIME) —— 這種類型的Annotations將被JVM保留,所以他們能在運(yùn)行時(shí)被JVM或其他使用反射機(jī)制的代碼所讀取和使用.
定義切面
/**
* @author Axin
*/
@Aspect
@Component
public class AxinAspect {
/**
* 這里定義了一個(gè)總的匹配規(guī)則,以后攔截的時(shí)候直接攔截log()方法即可,無(wú)須去重復(fù)寫execution表達(dá)式
*/
@Pointcut("@annotation(Axin)")
public void log() {
}
@Before("log()&&@annotation(axin)")
public void doBefore(JoinPoint joinPoint,Axin axin) {
System.out.println("******攔截前的邏輯******");
System.out.println("目標(biāo)方法名為:" + joinPoint.getSignature().getName());
System.out.println("目標(biāo)方法所屬類的簡(jiǎn)單類名:" + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("目標(biāo)方法所屬類的類名:" + joinPoint.getSignature().getDeclaringTypeName());
System.out.println("目標(biāo)方法聲明類型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
//獲取傳入目標(biāo)方法的參數(shù)
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
System.out.println("第" + (i + 1) + "個(gè)參數(shù)為:" + args[i]);
}
System.out.println("被代理的對(duì)象:" + joinPoint.getTarget());
System.out.println("代理對(duì)象自己:" + joinPoint.getThis());
System.out.println("攔截的注解的參數(shù):");
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("環(huán)繞通知:");
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("******攔截后的邏輯******");
}
}
匹配規(guī)則:
//匹配AOP對(duì)象的目標(biāo)對(duì)象為指定類型的方法,即DemoDao的aop的代理對(duì)象
@Pointcut("this(com.hhu.DemaoDao)")
public void thisDemo() {
...
}
通知類別:
前置通知(Before advice)- 在目標(biāo)方便調(diào)用前執(zhí)行通知
后置通知(After advice)- 在目標(biāo)方法完成后執(zhí)行通知
返回通知(After returning advice)- 在目標(biāo)方法執(zhí)行成功后,調(diào)用通知
異常通知(After throwing advice)- 在目標(biāo)方法拋出異常后,執(zhí)行通知
環(huán)繞通知(Around advice)- 在目標(biāo)方法調(diào)用前后均可執(zhí)行自定義邏輯
獲取上下文信息JoinPoint
JoinPoint對(duì)象封裝了SpringAop中切面方法的信息,在切面方法中添加JoinPoint參數(shù),就可以獲取到封裝了該方法信息的JoinPoint對(duì)象. 注意:這用于非環(huán)繞通知
| 方法名 | 功能 |
|---|---|
| Signature getSignature(); | 獲取封裝了署名信息的對(duì)象,在該對(duì)象中可以獲取到目標(biāo)方法名,所屬類的Class等信息 |
| Object[] getArgs(); | 獲取傳入目標(biāo)方法的參數(shù)對(duì)象 |
| Object getTarget(); | 獲取被代理的對(duì)象 |
| Object getThis(); | 獲取代理對(duì)象 |
方法使用模板:
public void doBefore(JoinPoint joinPoint) {
System.out.println("******攔截前的邏輯******");
System.out.println("目標(biāo)方法名為:" + joinPoint.getSignature().getName());
System.out.println("目標(biāo)方法所屬類的簡(jiǎn)單類名:" + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("目標(biāo)方法所屬類的類名:" + joinPoint.getSignature().getDeclaringTypeName());
System.out.println("目標(biāo)方法聲明類型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
//獲取傳入目標(biāo)方法的參數(shù)
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
System.out.println("第" + (i + 1) + "個(gè)參數(shù)為:" + args[i]);
}
System.out.println("被代理的對(duì)象:" + joinPoint.getTarget());
System.out.println("代理對(duì)象自己:" + joinPoint.getThis());
}
ProceedingJoinPoint
ProceedingJoinPoint對(duì)象是JoinPoint的子接口,該對(duì)象只用在@Around的切面方法中
| 方法名 | 功能 |
|---|---|
| Object proceed() throws Throwable | 執(zhí)行目標(biāo)方法 |
| Object proceed(Object[] var1) throws Throwable | 傳入的新的參數(shù)去執(zhí)行目標(biāo)方法 |
定義測(cè)試方法
//Service接口
public interface AxinService {
String axinRun(String arg1, User user);
}
//實(shí)現(xiàn)類
/**
* @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;
}
}
測(cè)試結(jié)果
環(huán)繞通知:
打印
******攔截前的邏輯******
目標(biāo)方法名為:axinRun
目標(biāo)方法所屬類的簡(jiǎn)單類名:AxinService
目標(biāo)方法所屬類的類名:com.axin.springboot.service.AxinService
目標(biāo)方法聲明類型:public abstract
第1個(gè)參數(shù)為:Test:
第2個(gè)參數(shù)為:User(id=null, name=張三, age=10, date=null)
被代理的對(duì)象:com.axin.springboot.service.AxinServiceImpl@ac2ddcc
代理對(duì)象自己:com.axin.springboot.service.AxinServiceImpl@ac2ddcc
攔截的注解的參數(shù):
打印
******攔截后的邏輯******
小結(jié)
通過(guò)上述的代碼演示,我們可以自定義一個(gè)注解,然后配置切面來(lái)攔截有注解的方法,同時(shí)也可以獲得方法傳入的參數(shù)來(lái)完成你的業(yè)務(wù)需求。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot+Jersey跨域文件上傳的實(shí)現(xiàn)示例
在SpringBoot開發(fā)后端服務(wù)時(shí),我們一般是提供接口給前端使用,本文主要介紹了SpringBoot+Jersey跨域文件上傳的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-07-07
java實(shí)現(xiàn)遍歷樹形菜單兩種實(shí)現(xiàn)代碼分享
這篇文章主要介紹了java實(shí)現(xiàn)遍歷樹形菜單兩種實(shí)現(xiàn)代碼分享,兩種實(shí)現(xiàn):OpenSessionView實(shí)現(xiàn)、TreeAction實(shí)現(xiàn)。具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
如何利用Retrofit+RxJava實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求的異常處理
這篇文章主要介紹了如何利用Retrofit+RxJava實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求的異常處理,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-04-04
java開發(fā)MyBatis中常用plus實(shí)體類注解符詳解
這篇文章主要為大家介紹了java開發(fā)MyBatis常用的plus實(shí)體類注解符示例應(yīng)用詳解有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10
mybatis plus使用redis作為二級(jí)緩存的方法
這篇文章主要介紹了mybatis plus使用redis作為二級(jí)緩存的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09
Java Web項(xiàng)目中Spring框架處理JSON格式數(shù)據(jù)的方法
Spring MVC是個(gè)靈活的框架,返回JSON數(shù)據(jù)的也有很多五花八門的方式,這里我們來(lái)整理一個(gè)最簡(jiǎn)單的Java Web項(xiàng)目中Spring框架處理JSON格式數(shù)據(jù)的方法:2016-05-05

