SpringAOP 通知(adivce)- methodIntercepor

环绕通知(即methodIntercepor) 是SpringAOP 通知模块中的一种通知方式。可用在指定方法执行之前,执行之后。对于同时要实现两种通知的方法是一种便利。若使用BeforeAdivce和afterreturningadvice则显得太多与繁琐。
可通过实现MethodInterceptor接口来实现环绕通知。

1.MethodInterceptor接口源代码

public interface MethodInterceptor extends Interceptor {
    Object invoke(MethodInvocation var1) throws Throwable;
}

2.具体小案例实现环绕通知。

2.1 具体的业务类
   /**
     * 目标业务类

     * Created by engle on 16-5-14.
     */
    public class Target{

        public void log() {
            System.out.println("日志信息");
        }
    }
2.2 环绕通知实现类
/**
 * Created by engle on 16-5-14.
 */
public class InterceptorMessage implements MethodInterceptor {

    /**
     *
     * @param methodInvocation 调用方法对象
     * @return 放回的对象
     * @throws Throwable 抛出的异常
     */
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {

        System.out.println("在目标方法执行的之前的环绕通知");
        Object proceed = methodInvocation.proceed(); //通过反射机制获取代理对象执行的方法
        System.out.println("在目标方法执行之后的环绕通知");
        return proceed;
    }
}
2.3测试类
/**
 * 测试类
 * Created by engle on 16-5-14.
 */
public class Test {
    public static void main(String[] args) {

        Target target = new Target();
        BeforeAdvice before = new BeforeMessage();
        AfterMessage after = new AfterMessage();
        MethodInterceptor interceptor = new InterceptorMessage();

        ProxyFactory factory = new ProxyFactory();  //设置代理工厂
        factory.addAdvice(interceptor);
        factory.setTarget(log);     //添加执行目标信息
        Target proxy = (Target) factory.getProxy(); //获取代理对象
        proxy.log();

    }
}
2.4测试结果
在目标方法执行的之前的环绕通知
日志信息
在目标方法执行之后的环绕通知
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值