spring recipes笔记 - 使用动态代理模块化横切关注点

因为非模块化的横切关注点会导致代码的混乱和代码的分散,所以我们都希望有一种能将其模块化的方法。

在这里我们选择代理设计模式将横切关注点从核心关注点分离出去,代理设计模式的原理是使用一个代理将对象包装起来,然后用该代理对象取代原来的对象,任何对原来的对象调用都首先要通过代理,与此同时,围绕着每个方法的调用,代理对象也可以执行一些额外的人物,代理非常适合实现横切关注点。

还是上面计算器的例子,我们创建一个日志代理,通过实现InvocationHandler接口,可以编写一个记录方法的开始和结束调用的处理程序。


public class ComputeLoggingHandler implements InvocationHandler{
private Log log = LogFactory.getLog(this.getClass());

private Object target;

public ComputeLoggingHandler(Object target){
this.target = target;
}

public static Object createProxy(Object target){
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),new ComputeLoggingHandler(target));
}

public Object invoke(Object arg0, Method method, Object[] arg2)
throws Throwable {
// TODO Auto-generated method stub
log.info("the method "+method.getName()+"() start");
System.out.println("the method "+method.getName()+"() start");
Object result = method.invoke(target, arg2);
log.info("the method "+method.getName()+"() end"+result);
System.out.println("the method "+method.getName()+"() end"+result);
return null;
}

}

public class Main {

public static void main(String args[]){

Compute computeImpl = new ComputeImpl();
Compute compute = (Compute)ComputeLoggingHandler.createProxy(computeImpl);
compute.add(1, 2);
}
}


我们通过ComputeLoggingHandler代理实现InvocatonHandler接口invoke()方法,它允许控制整个调用过程
Invoke方法第一个参数是代理实例,正在调用的是它的方法。
第二个参数是method方法对象,代表当前正被调用的方法。
第三个参数是北调用的目标方法的参数数组。
最后作为当前方法调用的结果,必须返回一个值。

下一篇:spring recipes笔记 - 使用经典的spring通知来模块化横切关注点
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值