简单测试AOP五种增强执行时机

1. 目标方法类,spring代理bean

@Component
public class Test {
    public void test(){
        System.out.println("test 目标方法");
    }

    public void testException(){
        throw new RuntimeException();
    }
}

2. 配置类

@Configuration
@ComponentScan
@EnableAspectJAutoProxy //启用apsectJ的自动代理
public class Config {
}

3. 切面类

        对测试类Test中的test()和testException()方法分别进行测试,并输出,以观察增强方法的执行顺序。

@Aspect  //切面类
@Component
public class AspectOrder {
    @Pointcut("execution(* org.example.test.*.test*(..))")//表示匹配test包下的所有类的test*方法
    private void a() {}
    @Before("a()")//before(切入点表达式)
    public void before() {
        System.out.println("before");
    }
    @Around("a()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        System.out.println("Around 开始。。。");
        //运行目标方法
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        System.out.println("Around 结束。。。");
        return proceed;
    }

    @AfterThrowing(throwing = "e", pointcut = "a()")
    public void doAfterThrowing(RuntimeException e) {
        System.out.println("出现异常:" + e.getMessage());
    }

    @AfterReturning(value = "a()",returning = "retVal") //正常返回执行 returning = "retVal"为返回值
    public void doAfterReturning(Object retVal) {
        System.out.println("AfterReturning");
        
    }

    @After("a()")
    public void doAfter() {
        System.out.println("after");
    }
}

4. 测试类

        测试aop五种增强方法执行顺序。

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        Test test = (Test) context.getBean("test");
//        test.test();//无异常
        test.testException();//有异常
    }
}

5. 测试结果

        1. 无异常时,各增强方法执行结果

        2. 有异常时,各增强方法执行结果

6. 结论

        1. 无异常时,执行顺序为:环绕增强(前)-> 前置增强 -> 目标方法 -> 返回增强 -> 后置增强 -> 环绕增强(后)

        2. 有异常时,执行顺序为:环绕增强(前)-> 前置增强 -> 目标方法 -> 异常增强 -> 后置增强 。

有待补充....

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

睆小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值