代理模式(靜態(tài)): 一個接口,兩個實現類A(代理類)和B(業(yè)務類),A類持有B類,這兩個類方法相同,那么A類方法內部調用B類的方法,就可以在B類核心業(yè)務前后進行前置處理、后置處理,異常環(huán)繞處理等等。
Jdk動態(tài)代理要求必須有接口I和實現類B(業(yè)務類),那么通過jdk動態(tài)代理生成的類就是類A(代理類),上面代理模式是靜態(tài)代理,這里就是動態(tài)代理,代碼運行時候會生成一個代理類。
Cglib動態(tài)代理不要求有接口I只需要一個核心業(yè)務類B,那么通過cglib動態(tài)代理生成的類就是類A(代理類), 同上。
JDK動態(tài)代理示例:
public static void main(String[] args) {
//核心業(yè)務類B
IBooService B = new BooServiceImpl();
//生成的代理類A
Object A = Proxy.newProxyInstance(IBooService.class.getClassLoader(), new Class[]{IBooService.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//代理類方法的通用處理邏輯
System.out.println("開始事物");
//調用核心業(yè)務類B的方法
ReflectionUtils.invokeMethod(method, B, args);
System.out.println("提交事物");
return method.getName();
}
});
//調用代理類A方法
IBooService bs = (IBooService)A;
bs.check();
}
輸出結果:
開始事物
2018-08-16 10:30:44.161 [main] INFO com.tx.test.service.impl.BooServiceImpl - check()
提交事物
Cglib動態(tài)代理示例:
Enhancer enhancer = new Enhancer();
//設置業(yè)務類B
enhancer.setSuperclass(FooServiceImpl.class);
//設置回調
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) throws Throwable {
Long bTime = System.currentTimeMillis();
System.out.println("開始毫秒:"+ bTime);
//調用業(yè)務類B方法
proxy.invokeSuper(object, args);
Long eTime = System.currentTimeMillis();
System.out.println("結束毫秒:"+ bTime);
Long mills = eTime - bTime;
System.out.println("毫秒:"+ mills);
return mills;
}
});
//生成代理類A
Object A = enhancer.create();
IFooService fs1 = (FooServiceImpl) A;
//調用代理A方法
fs1.check();
運行結果:
開始毫秒:1534387476396
2018-08-16 10:44:36.403 [main] INFO com.tx.test.service.impl.FooServiceImpl - check()
結束毫秒:1534387476396
毫秒:7
完!
posted on 2018-08-16 10:46
朔望魔刃 閱讀(201)
評論(0) 編輯 收藏 所屬分類:
java