Spring Boot aop使用指南

1. 使用示例

1.在pom中添加依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.使用aop注解

public class Test{
    public static void main(String[] args) {
        ApplicationContext ac = (ApplicationContext) new AnnotationConfigApplicationContext(Cfg.class);
        Target target = (Target) ac.getBean("target");
        target.print();
    }
}
@Configuration
@ComponentScan("com.example.springboot")
class Cfg{

}
@Component 
class Target{
    public void print(){
        System.out.println("target print");
    }
}

@Aspect
@Component // 必须纳入容器管理
class MyAspect{
    @Before("execution(* com.example.springboot.Target.print())")
    public void before(){
        System.out.println("before print");
    }
}

2. 增强类型

@Before 
@AfterReturning
@AfterThrowing
@After // 其实是AfterFinally增强
@Around // 环绕增强
原文地址:https://www.cnblogs.com/memo20/p/13140593.html