摘要:
本文通过一个问题“基于@Aspect的Spring AOP实现竟然没有运行”的调试全过程,给出了Spring最基础最“直觉”最“特别”的调试思路:考虑对象是否被框架加载/实例化了?
比较了解Spring AOP的同学可以直接看第二部分“2. 调试思路总结”。阅读本文大概需要10min。
文章目录
1. 基于@Aspect的Spring AOP实现为什么没有运行
1.1 基于@Aspect的Spring AOP实现代码
这是一个用IntelliJ IDEA开发的使用Maven搭建Spring Boot应用。
AnnotationApplication.java的源码:
package com.aop.annotation;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import java.util.Arrays;
@SpringBootApplication
public class AnnotationApplication {
public static void main(String[] args) {
SpringApplication.run(AnnotationApplication.class, args);
}
}
Operation.java是AOP的目标对象,即符合PointCut所指定的条件,被AOP织入横切逻辑(Advice)的对象。
package com.aop.annotation;
import org.springframework.stereotype.Component;
@Component
public class Operation {
public int add(int operand1, int operand2) throws Exception {
System.out.println("add operation.");
int result = operand1 + operand2;
if (result < 10) {
throw new Exception("not valid result.");
} else {
System.out.println("The result is: " + result);
return result;
}
}
public void show() {
System.out.println("function show().");
}
}
BeforeAdvice.java 是定义了Before Advice的Aspect对象。