官方网站: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("##############################################");
}