当前位置:  首页>> 技术小册>> Spring AOP 编程思想(上)

章节:API实现三种After Advice

在Spring AOP(面向切面编程)的广阔领域中,Advice(通知)是核心概念之一,它定义了横切关注点(cross-cutting concerns)的行为,如日志记录、事务管理、安全检查等。After Advice,作为Advice的一种类型,特指在目标方法执行之后(无论成功与否)执行的代码。Spring AOP提供了多种After Advice的实现方式,其中最为基础和常用的三种是:AfterReturningAdviceAfterThrowingAdviceAfterAdvice(通常指的是AfterReturningAdviceAfterThrowingAdvice之外的通用After Advice,但在Spring AOP中,更具体地,我们可能会通过MethodInterceptorAround Advice来模拟这一行为,因为Spring AOP直接API中并没有一个名为AfterAdvice的接口)。本章节将详细探讨如何通过Spring AOP的API来实现这三种After Advice。

1. AfterReturningAdvice

AfterReturningAdvice是Spring AOP中用于在目标方法正常执行完毕后执行的通知。它允许你访问方法的返回值(如果有的话),并基于这个返回值执行一些操作。实现AfterReturningAdvice接口需要实现其afterReturning方法,该方法会在目标方法正常返回后调用。

实现步骤

  1. 定义AfterReturningAdvice
    创建一个类实现AfterReturningAdvice接口,并实现afterReturning方法。你需要指定该方法对哪些方法调用生效(通过方法签名匹配),并处理返回值。

    1. import org.aopalliance.intercept.AfterReturningAdvice;
    2. import org.aopalliance.intercept.MethodInvocation;
    3. public class MyAfterReturningAdvice implements AfterReturningAdvice {
    4. @Override
    5. public void afterReturning(Object returnValue, MethodInvocation mi) throws Throwable {
    6. // 可以在这里处理返回值returnValue
    7. System.out.println("Method " + mi.getMethod().getName() + " executed successfully. Return value: " + returnValue);
    8. }
    9. // 需要实现的方法签名匹配逻辑(通常通过配置实现)
    10. }
  2. 配置Advice
    在Spring配置文件中或通过注解配置MyAfterReturningAdvice,指定它应用于哪些方法。

    1. <!-- XML配置方式 -->
    2. <bean id="myAfterReturningAdvice" class="com.example.MyAfterReturningAdvice"/>
    3. <aop:config>
    4. <aop:advisor advice-ref="myAfterReturningAdvice"
    5. pointcut="execution(* com.example.service.*.*(..))"/>
    6. </aop:config>

    或者,使用注解方式(假设Spring Boot环境):

    1. @Aspect
    2. @Component
    3. public class MyAspect {
    4. @AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "returnValue")
    5. public void afterReturningAdvice(JoinPoint joinPoint, Object returnValue) {
    6. System.out.println("Method " + joinPoint.getSignature().getName() + " executed successfully. Return value: " + returnValue);
    7. }
    8. }

2. AfterThrowingAdvice

AfterThrowingAdvice用于在目标方法抛出异常时执行。它允许你访问抛出的异常对象,并据此执行特定的逻辑,如记录错误日志、发送警报等。

实现步骤

  1. 定义AfterThrowingAdvice
    创建一个类实现AfterThrowingAdvice接口(实际上,由于Spring AOP的API设计,更常见的是使用@AfterThrowing注解在Aspect类中定义)。不过,为了说明原理,我们可以模拟这一过程。

    1. // 注意:Spring AOP没有直接的AfterThrowingAdvice接口,这里仅作概念说明
    2. public class MyAfterThrowingAdvice {
    3. // 在实际使用中,你会通过@AfterThrowing注解在Aspect类中定义此方法
    4. public void afterThrowing(Throwable ex) {
    5. System.out.println("An exception occurred: " + ex.getMessage());
    6. }
    7. }

    但在Spring AOP中,你通常会这样做:

    1. @Aspect
    2. @Component
    3. public class MyAspect {
    4. @AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "ex")
    5. public void afterThrowingAdvice(JoinPoint joinPoint, Throwable ex) {
    6. System.out.println("Method " + joinPoint.getSignature().getName() + " threw an exception: " + ex.getMessage());
    7. }
    8. }
  2. 配置Advice
    配置方式与AfterReturningAdvice类似,但注意@AfterThrowing注解的使用。

3. 通用After Advice(通过Around Advice模拟)

虽然Spring AOP API没有直接提供一个名为AfterAdvice的接口来同时覆盖正常返回和异常抛出的情况,但你可以通过Around Advice(环绕通知)来模拟这一行为。Around Advice允许你在目标方法执行前后插入自定义行为,包括处理正常返回和异常抛出的情况。

实现步骤

  1. 定义Around Advice
    使用@Around注解定义一个环绕通知,在其中你可以控制目标方法的执行,并在其前后执行自定义逻辑。

    1. @Aspect
    2. @Component
    3. public class MyAspect {
    4. @Around("execution(* com.example.service.*.*(..))")
    5. public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
    6. try {
    7. Object result = pjp.proceed(); // 执行目标方法
    8. // 处理正常返回
    9. System.out.println("Method " + pjp.getSignature().getName() + " executed successfully. Return value: " + result);
    10. return result;
    11. } catch (Throwable ex) {
    12. // 处理异常抛出
    13. System.out.println("Method " + pjp.getSignature().getName() + " threw an exception: " + ex.getMessage());
    14. throw ex; // 可以选择重新抛出异常或进行其他处理
    15. }
    16. }
    17. }
  2. 配置Aspect
    确保Aspect类被Spring容器管理,并正确配置了AspectJ自动代理。

总结

通过AfterReturningAdvice@AfterThrowing注解(虽然不直接对应一个接口,但它是实现After Throwing Advice的主要方式),以及利用Around Advice模拟的通用After Advice,Spring AOP提供了灵活而强大的机制来处理目标方法执行后的各种情况。这些机制使得开发者能够轻松地将横切关注点从业务逻辑中分离出来,从而提高代码的可维护性和可重用性。在实际应用中,根据具体需求选择合适的Advice类型,并合理配置,是实现高效、清晰AOP编程的关键。


该分类下的相关小册推荐: