jdk的动态代理主要涉及的到java.lang.reflect包中的: Proxy 和 InvocationHandler 这两个类
PerformanceMonitor:
package com.baobaotao.service.proxy;
public class PerformanceMonitor {
private static ThreadLocal<MethodPerformance> performanceRecord = new ThreadLocal<MethodPerformance>();
public static void begin(String method) {
System.out.println("begin monitor...");
MethodPerformance mp = new MethodPerformance(method);
performanceRecord.set(mp);
}
public static void end() {
System.out.println("end monitor...");
MethodPerformance mp = performanceRecord.get();
mp.printPerformance();
}
}
MethodPerformance:
package com.baobaotao.service.proxy;
public class MethodPerformance {
private long begin;
private long end;
private String serviceMethod;
public MethodPerformance(String serviceMethod) {
this.serviceMethod = serviceMethod;
this.begin = System.currentTimeMillis();
}
public void printPerformance() {
end = System.currentTimeMillis();
long elapse = end - begin;
System.out.println(serviceMethod + "花费" + elapse + "毫秒");
}
}
PerformanceHandler
package com.baobaotao.service.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class PerformanceHandler implements InvocationHandler{
private Object target;
public PerformanceHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//PerformanceMonitor是自己定义的一个监听类
PerformanceMonitor.begin(target.getClass().getName() + "." + method.getName());
Object obj = method.invoke(target, args);
PerformanceMonitor.end();
return obj;
}
}
TestForumService:
package com.baobaotao.service.proxy;
import java.lang.reflect.Proxy;
import com.baobaotao.service.proxy.impl.ForumServiceImpl;
public class TestForumService {
public static void main(String[] args) {
//希望被代理的目标业务类
ForumService target = new ForumServiceImpl();
//将目标类与横切代码编织到一起
PerformanceHandler handler = new PerformanceHandler(target);
//根据编织了目标业务类逻辑和性能监视横切逻辑的InvotationHandler实例创建代理实例
ForumService proxy = (ForumService)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
proxy.insert();
}
}