JDK動態代理
Spring的AOP實現用了Proxy和InvocationHandler,現在就介紹一下JDK動態代理。
自定義的InvocationHandler需要重寫3個函數。
1)構造函數,將代理對象傳入
2)invoke方法
3)getProxy方法
1、創建業務接口
public interface UserService{
public void add();
}
2、創建業務接口實現類
public class UserServiceImpl implements UserService{
public void add(){
System.out.println("-----add-----");
}
}
3、創建自定義的InvocationHandler
public class MyInvocationHandler implements InvocationHandler{
//目標對象
private Object target;
public MyInvocationHandler(Object target){
super();
this.target=target;
}
4、執行目標對象的方法
public Object invoke(Object proxy, Method method, Object [] args)throws Throwable {
System.out.println("-----before-----");
Object result=method.invoke(target,args);
System.out.println("----after-----");
}
5、獲取目標對象的代理對象
public Object getProxy(){
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),target.Class.getInstance(),this);
}
}
6、測試代理
public class ProxyTest{
@Test
public void testProxy()throws Throwable{
//實例化目標對象
UserService userService=new UserServiceImpl();
//實例化InvocationHandler
MyInvocaitonHanlder invovationHandler=new MyInvocationHandler(userService);
//根據目標對象生成代理對象
UserService proxy=(UserService) invocationHandler.getProxy();
//調用代理對象的方法
proxy.add();
}
}
7、測試結果
------before------
------add--------
------after-------

浙公網安備 33010602011771號