责任链模式在SpringAop中的使用

先模拟一下SpringAop中的责任链

public interface MethodInvocation {

    Object proceed() throws Throwable;
    
}

定义拦截器接口

public interface MethodInterceptor {

    Object invoke(MethodInvocation methodInvocation) throws Throwable;

}

定义前置通知,在目标方法调用前执行通知

public class MethodBeforeAdviceInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        System.out.println("I am BeforeAdvice");
        return mi.proceed();
    }
}

定义后置通知,在目标方法完成后执行通知

public class AspectJAfterAdvice implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        try {
            return mi.proceed();
        }
        finally {
            System.out.println("I am AfterAdvice");
        }
    }
}

中间类,拦截器链调用逻辑:

public class ReflectiveMethodInvocation implements MethodInvocation {

    List<MethodInterceptor> methodInterceptors;

    private int currentInterceptorIndex = -1;

    public ReflectiveMethodInvocation(List<MethodInterceptor> methodInterceptors) {
        this.methodInterceptors = methodInterceptors;
    }

    @Override
    public Object proceed() throws Throwable {

        if (currentInterceptorIndex == this.methodInterceptors.size() - 1) {
            System.out.println("真正的目标方法");
            return "目标方法执行";
        }
        MethodInterceptor methodInterceptor = this.methodInterceptors.get(++this.currentInterceptorIndex);
        return methodInterceptor.invoke(this);

    }
}

测试类:

public class Test {

    public static void main(String[] args) throws Throwable {
        AspectJAfterAdvice aspectJAfterAdvice = new AspectJAfterAdvice();
        MethodBeforeAdviceInterceptor methodBeforeAdviceInterceptor = new MethodBeforeAdviceInterceptor();
        List<MethodInterceptor> methodInterceptors = new ArrayList<>();
        methodInterceptors.add(methodBeforeAdviceInterceptor);
        methodInterceptors.add(aspectJAfterAdvice);

        ReflectiveMethodInvocation reflectiveMethodInvocation = new ReflectiveMethodInvocation(methodInterceptors);
        reflectiveMethodInvocation.proceed();
    }
}

执行结果:

参考博客参考博客

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值