java - SpringAOP中Advice的织入和执行问题

 吕骥源_342 发布于 2022-10-30 01:06

Bean类:

package aop.schema.advice.biz;

public class AspectBiz {
    
    public void biz() {
        System.out.println("AspectBiz biz.");
        throw new RuntimeException();
    }
}

Aspect类:

package aop.schema.advice;

import org.aspectj.lang.ProceedingJoinPoint;

public class MoocAspect {
    
    public void before() {
        System.out.println("MoocAspect before.");
    }
    
    public void afterReturning() {
        System.out.println("MoocAspect afterReturning.");
    }

    public void afterThrowing() {
        System.out.println("MoocAspect afterThrowing.");
    }

    public void after() {
        System.out.println("MoocAspect after.");
    }
    
    public Object around(ProceedingJoinPoint pjp) {
        Object obj = null;
        try {
            System.out.println("MoocAspect around 1.");
            obj = pjp.proceed();
            System.out.println("MoocAspect around 2.");
        } catch (Throwable e) {
//            e.printStackTrace();
        }
        return obj;
    }
}

配置文件:


http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    

    
    

    
        
            
            
            
            
            
            
        
    


测试类:

package aop;

import aop.schema.advice.Fit;
import aop.schema.advice.biz.AspectBiz;
import base.UnitTestBase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestAOPSchemaAdvice extends UnitTestBase {
    
    public TestAOPSchemaAdvice() {
        super("classpath:spring-aop-schema-advice.xml");
    }
    
    @Test
    public void testBiz() {
        AspectBiz biz = super.getBean("aspectBiz");
        biz.biz();
    }
}

现在的问题是:
按理说AspectBiz在执行biz()时抛出异常,afterThrowing()应该执行,然而当5个advice全开时testBiz()的执行结果是:

MoocAspect before.
MoocAspect around 1.
AspectBiz biz.
MoocAspect after.
MoocAspect afterReturning.

结果显示afterThrowing()并没有执行,执行的是afterReturning()。
更神奇的是,如果我注释掉before这个advice,再次运行testBiz()的结果是:

MoocAspect around 1.
AspectBiz biz.
MoocAspect afterThrowing.
MoocAspect after.

这下正常了。
为什么会这样呢?为什么before advice会影响到after-throwing advice的执行呢?
和SpringAOP对advice的织入方式有关吗?那么SpringAOP的织入方式又是什么样的呢?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有