您当前的位置: 首页 >  spring

星夜孤帆

暂无认证

  • 6浏览

    0关注

    626博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

责任链模式在SpringAop中的使用

星夜孤帆 发布时间:2021-06-03 21:06:21 ,浏览量:6

先模拟一下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 methodInterceptors;

    private int currentInterceptorIndex = -1;

    public ReflectiveMethodInvocation(List 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 methodInterceptors = new ArrayList();
        methodInterceptors.add(methodBeforeAdviceInterceptor);
        methodInterceptors.add(aspectJAfterAdvice);

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

执行结果:

参考博客、参考博客

 

 

 

 

 

 

 

 

关注
打赏
1636984416
查看更多评论
立即登录/注册

微信扫码登录

0.6914s