1. 首页
  2. 软件开发
  3. Srping——基于XML实现AOP的五种通知类型

Srping——基于XML实现AOP的五种通知类型

  • 发布于 2024-08-17
  • 0 次阅读

在基于XML配置的AOP中,可以使用五种主要的通知类型来实现横切关注点的功能:前置通知(Before)、后置通知(After)、返回通知(After-returning)、异常通知(After-throwing)和环绕通知(Around)。

1. 前置通知

  • 在目标方法执行前执行的通知。
<aop:config>
    <aop:aspect ref="loggingAspect">
        <aop:before method="beforeMethodExecution" pointcut="execution(* com.example.MyService.*(..))"/>
    </aop:aspect>
</aop:config>

2. 后置通知

  • 在目标方法执行后执行的通知,无论方法是否抛出异常。
<aop:config>
    <aop:aspect ref="loggingAspect">
        <aop:after method="afterMethodExecution" pointcut="execution(* com.example.MyService.*(..))"/>
    </aop:aspect>
</aop:config>

3. 返回通知

  • 在目标方法成功执行并返回结果后执行的通知。
<aop:config>
    <aop:aspect ref="loggingAspect">
        <aop:after-returning method="afterReturningMethodExecution" pointcut="execution(* com.example.MyService.*(..))"/>
    </aop:aspect>
</aop:config>

4. 异常通知

  • 在目标方法抛出异常时执行的通知。
<aop:config>
    <aop:aspect ref="loggingAspect">
        <aop:after-throwing method="afterThrowingMethodExecution" pointcut="execution(* com.example.MyService.*(..))"/>
    </aop:aspect>
</aop:config>

5. 环绕通知

  • 在目标方法执行前后都可以执行的通知,可以控制目标方法的执行。
<aop:config>
    <aop:aspect ref="loggingAspect">
        <aop:around method="aroundMethodExecution" pointcut="execution(* com.example.MyService.*(..))"/>
    </aop:aspect>
</aop:config>

原文链接: https://blog.csdn.net/2401_82884096/article/details/136977847