AOP,面向切面编程,它能把与核心业务逻辑无关的散落在各处并且重复的代码给封装起来,降低了模块之间的耦合度,便于维护。具体的应用场景有:日志,权限和事务管理这些方面。可以通过一张图来理解下:

spring AOP的用法

Spring AOP可以通过注解和xml配置的方式来实现,下面我们讲解下这两种不同的用法。

1.注解的方式

定义一个切面Operator

/**
 * 定义一个切面Operator:包含切入点表达式和通知
 */

@Component
@Aspect 
public class Operator {

    //定义切入点表达式
    @Pointcut("execution(* com.demo.aop..*.*(..))")
    public void pointCut() {
        
    };

    //以下都为通知
    //前置通知:在目标方法调用前执行
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        System.out.println("AOP before advice ...");
    }

    //在目标方法正常执行后做增强处理
    @AfterReturning("pointCut()")
    public void doAfterReturn(JoinPoint joinPoint) {
        System.out.println("AOP after return advice ...");
    }

    //环绕通知:在目标方法完成前后做增强处理
    @Around("pointCut()")
    public void around(ProceedingJoinPoint pjp) {
        System.out.println("AOP Around before...");
        try {
            pjp.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("AOP Aronud after...");
    }

    //在目标方法完成后做增强处理,无论目标方法是否成功完成
    @After("pointCut()")
    public void doAfter(JoinPoint joinPoint) {
        System.out.println("AOP after advice ...");
    }
    
    //用来处理发生的异常
    @AfterThrowing(pointcut="pointCut()",throwing="error")
    public void afterThrowing(JoinPoint joinPoint,Throwable error){
        System.out.println("AOP AfterThrowing Advice..." + error);
    }
    
    
}
View Code

相关文章:

  • 2022-12-23
  • 2021-08-06
  • 2022-12-23
  • 2021-12-27
  • 2021-11-27
  • 2021-12-24
  • 2021-09-12
猜你喜欢
  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
  • 2021-12-27
相关资源
相似解决方案