SpringAOP 通知(adivce)- methodIntercepor

    xiaoxiao2026-01-28  10

    环绕通知(即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测试结果 在目标方法执行的之前的环绕通知 日志信息 在目标方法执行之后的环绕通知
    最新回复(0)