java - SpringAOP中Advice的织入和执行问题
PHP中文网
PHP中文网 2017-04-18 09:38:07
[Java讨论组]

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;
    }
}

配置文件:




    

    
    

    
        
            
            
            
            
            
            
        
    


测试类:

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的织入方式又是什么样的呢?

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号