AOP(Apsect Oriented Programming),即面向切面编程,是一种开发思想,其主要是用来解决程序中的横切关注点问题。
在 Spring 中,AOP 主要使用的是基于代理的 AOP 实现,它是使用 JDK 动态代理或 CGLIB 动态代理来代理目标对象,然后基于代理对象来实现增强的功能。
下面是一个使用 Spring AOP 的详细例子:
1. 定义一个接口及其实现类
public interface Calculator {
public int add(int a, int b);
public int sub(int a, int b);
}
public class CalculatorImpl implements Calculator {
public int add(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
}
2. 定义一个切面类
public class LoggingAspect {
public void before(JoinPoint joinPoint){
System.out.println("before "+joinPoint.getSignature().getName()+"..("+ Arrays.toString(joinPoint.getArgs())+")");
}
public void after(JoinPoint joinPoint, Object result){
System.out.println("after "+joinPoint.getSignature().getName()+"..("+ Arrays.toString(joinPoint.getArgs())+") => "+result);
}
}
3. 配置 AOP
<!-- 配置切面 -->
<bean id="loggingAspect" class="com.example.aop.LoggingAspect" />
<!-- 定义一个 Pointcut,匹配 Calculator 接口的所有方法 -->
<aop:pointcut id="calculatorMethods" expression="execution(* com.example.aop.Calculator.*(..))" />
<!-- 配置 Advice -->
<aop:config>
<aop:aspect ref="loggingAspect">
<aop:before method="before" pointcut-ref="calculatorMethods" />
<aop:after-returning method="after" returning="result" pointcut-ref="calculatorMethods" />
</aop:aspect>
</aop:config>
4. 使用 AOP
// 获取 Spring 上下文
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:aop.xml");
// 从 Spring 上下文中获取 Calculator 的代理对象
Calculator calculator = (Calculator)context.getBean("calculator");
// 调用代理对象的方法
int result1 = calculator.add(1, 2); // 输出:before add..([1, 2]) after add..([1, 2]) => 3
int result2 = calculator.sub(3, 1); // 输出:before sub..([3, 1]) after sub..([3, 1]) => 2
以上就是一个 Spring AOP 的例子,主要涉及到三个部分:目标对象、切面类和配置 AOP。在 AOP 中,我们可以使用不同类型的 Advice(例如:before、after、around 等)来实现不同的操作,在这个例子中,我们使用了 before 和 after Advice 来实现日志记录。