`
cyz001
  • 浏览: 42560 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

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通知来模块化横切关注点
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics