结合上一篇文章([url=http://leh627.iteye.com/blog/828434]自定义annotation 实现注入功能[/url]),里面模拟了一个拦截器。
发现在使用的时候都需要去调用SimilarToTheInterceptor.scanAllFieldsAndMethods 方法,
如果说有多个action需要注入,很显然这是种不好的设计。
TestAction action = new TestAction();
SimilarToTheInterceptor.scanAllFieldsAndMethods(action);// 模拟拦截器功能
action.saveDate1();
于是我想到使用java.lang.reflect.Proxy 去实现这个拦截器功能
正对前一篇文章的代码下面几个类需要改变
1.SimilarToTheInterceptor 该名称 ScanHelper 内容保持不变
2.增加一个新类,用来实现 拦截功能
3,增加一个接口Action,然后TestAction去实现这个接口(由于proxy 必须要一个接口)
3 ,测试
4.结果
==========Saved======TestService_1 class was invoked
==========Saved======TestService_2 class was invoked
这样实现就很好的降低了耦合
发现在使用的时候都需要去调用SimilarToTheInterceptor.scanAllFieldsAndMethods 方法,
如果说有多个action需要注入,很显然这是种不好的设计。
TestAction action = new TestAction();
SimilarToTheInterceptor.scanAllFieldsAndMethods(action);// 模拟拦截器功能
action.saveDate1();
于是我想到使用java.lang.reflect.Proxy 去实现这个拦截器功能
正对前一篇文章的代码下面几个类需要改变
1.SimilarToTheInterceptor 该名称 ScanHelper 内容保持不变
2.增加一个新类,用来实现 拦截功能
package com.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class Handler implements InvocationHandler {
private Object obj;
public Handler(Object obj) {
this.obj = obj;
}
public static Object newInstance(Object obj) {
System.out.println(obj.getClass().getName());
return java.lang.reflect.Proxy.newProxyInstance(obj.getClass()
.getClassLoader(), obj.getClass().getInterfaces(),
new Handler(obj));
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
if(obj!=null){
ScanHelper.scanAllFieldsAndMethods(obj);// 注入
result = method.invoke(obj, args);
}
return result;
}
}
3,增加一个接口Action,然后TestAction去实现这个接口(由于proxy 必须要一个接口)
public interface Action {
public void saveDate1();
public void saveDate2();
}
3 ,测试
package com.test;
public class Main {
public static void main(String[] args) {
TestAction a = new TestAction();
Action action = (Action) Handler.newInstance(a);
action.saveDate1();
action.saveDate2();
}
}
4.结果
==========Saved======TestService_1 class was invoked
==========Saved======TestService_2 class was invoked
这样实现就很好的降低了耦合