首先先贴个总结比较好的一个博客:Spring AOP @Before @Around @After 等 advice 的执行顺序。但是其中有个错误,异常情况下,method执行完会直接执行@After 方法,而不会再执行@Around 后面的代码。所以,其中的图是有问题的。
1.单个方法被单个Aspect拦截
1.1 正常情况:
public interface Person {
String sayHello(String name);
void eat(String food);
}
@Component
public class Chinese implements Person {
@Timer
@Override
public String sayHello(String name) {
System.out.println("-- sayHello() --");
return name + " hello, AOP";
}
@Override
public void eat(String food) {
System.out.println("我正在吃:" + food);
// sayHello("hello");
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Timer {
}
@SpringBootApplication
@RestController
public class SpringBootDemoApplication {
//这里必须使用Person接口做注入
@Autowired
private Person chinese;
@RequestMapping("/test")
public void test() {
chinese.sayHello("listen");
System.out.println(chinese.getClass());
}
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);