接上一篇使用Spring AOP 的Aspectj 解析自定義注解,再解析之前需要先做一些準(zhǔn)備工作,要使用aspectj就必須啟動Spring.我這里使用Spring boot練習(xí)诅诱。依賴如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
這里繼續(xù)使用上一篇的ShowMessage注解 和AnnotationUtile類。
新增Spring boot 控制層 ServiceController類:
package com.annotation.controller;
import com.annotation.impl.AnnotationUtile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServiceController {
@Autowired
private AnnotationUtile annotationUtile;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String showMessage(){
annotationUtile.test();
return "這是一個測試";
}
}
新增aspectJ定義:
package com.annotation.aspect;
import com.annotation.annotation.ShowMessage;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* @Aspect 注解告訴Spring 該類是一個aspect
*/
@Aspect
@Component
public class ShowMessageAspect {
/**
* @Before 前置通知表示再方法執(zhí)行之前執(zhí)行
* 這個aspect 的概念這里不做過多描述。 @annotation是 aspect 表達(dá)式藻烤。
* @param showMessage
*/
@Before("@annotation(showMessage)")
public void before(ShowMessage showMessage){
System.out.println(showMessage.value());
}
}
這樣使用@ShowMessage時只需要再相應(yīng)的方法前加上注解就可以了武鲁,對了忘記測試下爽雄。這里使用postmain測試:
image.png
看到返回了來看看日志:
image.png
這樣就實現(xiàn)了自定義注解的功能,我個人比較喜歡使用Aspectj 處理自定義注解這種方式。定義完成后使用比較方便沐鼠,那用再哪里加注解就ok挚瘟。這里提到了AspectJ 稍后我想把 AspectJ也拉出來學(xué)習(xí)學(xué)習(xí)也會同時分享下。