spring AOP的用法

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

定义UserService类

@Service("userService")
public class UserService {
    
    public void add(){
        System.out.println("UserService add()");
    }
    
    public boolean delete(){
        System.out.println("UserService delete()");
        return true;
    }
    
}
    
View Code

执行以下代码:

@Test
    public void testAop(){
        @SuppressWarnings("resource")
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");//解析注册beanDefinition,然后实例化bean,再初始化bean
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.add();
    }
View Code

输出结果是:

AOP Around before...
AOP before advice ...
UserService add()
AOP Aronud after...
AOP after advice ...
AOP after return advice ...

所以由此,我们可以总结出通知的执行顺序:

无异常情况:around before -->before-->目标方法-->around after-->after-->afterReturn

扫描二维码关注公众号,回复: 1766030 查看本文章

有异常情况:around before -->before-->目标方法-->around after-->after-->afterThrowing 

猜你喜欢

转载自www.cnblogs.com/51life/p/9227868.html