上几篇提到分别提到了方法拦截器,和advice等通知,在上面的过程中,框架使用者通过实现MethodBeforeAdvice等接口来来表示
在操作某个方法之前或之后应该做什么,而我们的程序中通过方法拦截器来表示在方法之前或之后应该做什么,两者不一样?该如何解决呢? 不错,这时候就需要用到java的设计模式——适配器模式了
首先定义适配器接口,明确适配器的功能
package com.autoproxy.Adapter; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; /** * Created by zoujianglin * 2018/8/28 0028. */ public interface AdviceAdapter { //表明是否支持该advice boolean supportsAdvice(Advice advice); //适配为拦截器返回 MethodInterceptor getInterceptor(Advice advice); }
为有3中不同的advice故有3个不同的适配器,分别将不同的advice适配为对应的methodInterceptor,具体实现如下
package com.autoproxy.Adapter; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; /** * Created by zoujianglin * 2018/8/28 0028. * 适配器,将advice适配为拦截器,从而方便处理 */ public class MethodBeforeAdviceAdapter implements AdviceAdapter { public boolean supportsAdvice(Advice advice) { return advice instanceof MethodBeforeAdvice; } public MethodInterceptor getInterceptor(Advice advice1) { MethodBeforeAdvice advice = (MethodBeforeAdvice) advice1; return new MethodBeforeAdviceInterceptor(advice); } }
package com.autoproxy.Adapter; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; /** * Created by zoujianglin * 2018/8/29 0029. */ public class AfterReturningAdviceAdapter implements AdviceAdapter { public boolean supportsAdvice(Advice advice) { return advice instanceof AfterReturningAdice; } public MethodInterceptor getInterceptor(Advice advice1) { AfterReturningAdice advice = (AfterReturningAdice) advice1; return new AfterReturningAdviceInterceptor(advice); } }
package com.autoproxy.Adapter; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; /** * Created by zoujianglin * 2018/8/29 0029. */ public class ThrowsAdviceAdapter implements AdviceAdapter { public boolean supportsAdvice(Advice advice) { return advice instanceof ThrowsAdvice; } public MethodInterceptor getInterceptor(Advice advice) { ThrowsAdvice throwsAdvice = (ThrowsAdvice) advice; return new ThrowsAdviceInterceptor(throwsAdvice); } }