官方網站:https://docs.spring.io/spring/docs/5.0.17.RELEASE/spring-framework-reference/core.html#aop
1、加入依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、使用聲明式使用AOP,核心註解:
@Aspect:修飾在切面類上,指定切面
@PoitCut:修飾在方法上,指定切入點
- execution - 用於匹配方法執行連接點,這是在使用Spring AOP時將使用的主要切入點指示符
- within - 限制匹配某些類型內的連接點(僅在使用Spring AOP時在匹配類型內聲明的方法的執行)
- this - 限制匹配到連接點(使用Spring AOP時方法的執行),其中bean引用(Spring AOP代理)是給定類型的實例
- target - 限制匹配到連接點(使用Spring AOP時方法的執行),其中目標對象(代理的應用程序對象)是給定類型的實例
- args - 限制匹配的連接點(使用Spring AOP時方法的執行),其中參數是給定類型的實例
- @target - 限制匹配的連接點(使用Spring AOP時方法的執行),其中執行對象的類具有給定類型的註釋
- @args - 限制匹配的連接點(使用Spring AOP時方法的執行),其中傳遞的實際參數的運行時類型具有給定類型的註釋
- @within - 限制匹配到具有給定註釋的類型中的連接點(使用Spring AOP時,使用給定註釋的類型中聲明的方法的執行)
- @annotation - 將匹配點限制爲其中連接點的主題(在Spring AOP中執行的方法)具有給定註釋的連接點
例子:
@Aspect
@Component
public class GlobalControllerResponse {
// @Pointcut("execution(public io.gao.training.web.myboot.controller..*)")
@Pointcut("within(io.gao.training.web.myboot.controller.*) && execution(* list())")
public void poitCut(){
}
@Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping)")
public void poitCutForAnotation(){
}
@Before(value = "poitCut()")
public void before(){
System.out.println("##############################################");
System.out.println("GlobalControllerResponse.before");
System.out.println("##############################################");
}
@Before(value = "poitCutForAnotation()")
public void before2(){
System.out.println("##############################################");
System.out.println("GlobalControllerResponse.before2");
System.out.println("##############################################");
}