Spring之手写 Aop(4)

上几篇提到分别提到了方法拦截器,和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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值