继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Spring-AOP

冰狐
关注TA
已关注
手记 20
粉丝 1
获赞 31

增强时机

代理类

try{
    before(前置增强)
    被增强的方法;(环绕增强针对方法内部)
    after-returning(后置增强)
} catch(Exception e){
    after-throwing(异常增强)
} finally{
    after(最终增强)
}

环绕增强

1. 方法必须用Object作为返回值
2. 方法第一个参数为ProceedingJoinPoint
public Object aroundAdvice(ProceedingJoinPoint pj) throws Throwable {
    //获得方法的参数
    Object[] args = pj.getArgs();
    //根据参数做一些处理
    System.out.println("HelloAspect.aroundAdvice");
    //调用实际的方法
    pj.proceed();
    return null;
}

xml配置文件

切点pointcut:在哪些包-->哪些类-->哪些方法
连接点(在方法的哪些位置上):before,after-returning,after-throwing,after
用哪些方法增强:"beforAdvice","afterAdvice","throwExceptionAdvice","finallyAdvice"
一个切面包含上述三点
<bean id="aspect" class="com.xxx.testaop.HelloAspect"/>
<aop:config>
    <aop:pointcut id="pointcut" expression="execution(* com.xxx.testaop.*.*(..))"/>
    <aop:aspect ref="aspect">
        <aop:before method="beforAdvice" pointcut-ref="pointcut"/>
        <aop:after-returning method="afterAdvice" pointcut-ref="pointcut"/>
        <aop:after-throwing method="throwExceptionAdvice" pointcut-ref="pointcut"/>
        <aop:after method="finallyAdvice" pointcut-ref="pointcut"/>
        <aop:around method="aroundAdvice" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>

增强实现类

public class HelloAspect {
    public void beforAdvice(){
        System.out.println("HelloAspect.beforAdvice");
    }

    public void afterAdvice(){
        System.out.println("HelloAspect.afterAdvice");
    }

    public void throwExceptionAdvice(){
        System.out.println("HelloAspect.throwExceptionAdvice");
    }

    public void finallyAdvice(){
        System.out.println("HelloAspect.finallyAdvice");
    }

    public Object aroundAdvice(ProceedingJoinPoint pj) throws Throwable {
        Object[] args = pj.getArgs();
        System.out.println(pj.getKind());
        System.out.println(pj.getThis());
        pj.proceed();
        System.out.println("HelloAspect.aroundAdvice");
        return null;
    }
}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP