Spring中面向切面的编程

一个约定游戏,即通过java的jdk动态代理实现代理类,用代理类调用方法

POJO:

public class MyRole {
    private String name;
    private String note;

   setter/getter....
}

一个接口 

public interface Service {
    public void printInfo();
}

接口的实现类

public class ServiceImpl implements Service {
    private MyRole role;

    public ServiceImpl(MyRole role){
        this.role = role;
    }
    @Override
    public void printInfo() {
        System.out.println("调用子类方法");

    }
}

一个拦截器接口:

public interface Interceptor {
    public void before(Object obj);
    public void after(Object obj);
    public void afterReturning(Object obj);
    public void afterThrowing(Object obj);
}

拦截器接口的实现:

public class MyInterceptor implements Interceptor {
    @Override
    public void before(Object obj) {
        System.out.println("before...");
    }

    @Override
    public void after(Object obj) {
        System.out.println("After....");
    }

    @Override
    public void afterReturning(Object obj) {
        System.out.println("afterReturning...");
    }

    @Override
    public void afterThrowing(Object obj) {
        System.out.println("afterThrowing...");
    }
}

动态代理

public class MyProxy implements InvocationHandler {
    private Service service = null;
    private Interceptor interceptor = null;
    //返回一个代理对象
    public Object getProxy(Object target,Interceptor interceptor){
        service = (Service) target;
        this.interceptor = interceptor;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object retObj = null;
        boolean flag = false;
        interceptor.before(null);
        try{
                retObj = method.invoke(service,args);

        }catch (Exception e){
            flag = true;

        }finally {
            interceptor.after(null);
        }
        if(flag){
            interceptor.afterThrowing(null);
        }else {
            interceptor.afterReturning(null);
        }
        System.out.println(retObj);
        return retObj;
    }
}

代码测试:

public class TestMain {
    public static void main(String[] args) {
        MyRole role = new MyRole();
        role.setName("role1");
        role.setNote("role_note");
        Interceptor interceptor = new MyInterceptor();
        Service service = new ServiceImpl(role);
        Service proxy = (Service)new MyProxy().getProxy(service, interceptor);
        proxy.printInfo();

    }
//    Service service = new ServiceImpl();
}

运行结果如图:

该游戏其实就是AOP的核心思想,通过动态代理实现代码的织入,从而实现调用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值