Spring動態代理
就是InvocationHandler和Proxy兩個類,Proxy是生成動態代理例項的;InvocationHandler是呼叫處理程式並返回結果的。
API中說明:
`import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
-
@author hxd
-
@create 2021-07-10 15:38
*/
//用這個類自動生成代理類
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的介面
private Object target;public void setTarget(Object target) {
this.target = target;
}//生成得到代理類
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}//處理代理例項,並返回結果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
return method.invoke(target, args);
}public void log(String msg) {
System.out.println("執行了:" + msg + "方法");
}
}
`
`import com.kuang.demo2.UserService;
import com.kuang.demo2.UserServiceImpl;
import org.junit.Test;
/**
-
@author hxd
-
@create 2021-07-10 15:40
*/
public class Client {
@Test
public void test() {
//真實角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色,不存在
ProxyInvocationHandler handler = new ProxyInvocationHandler();
//設定要代理的物件
handler.setTarget(userService);
//動態生成代理類
UserService target = (UserService) handler.getProxy();target.add();
}
}`
動態代理的好處:
- 靜態代理有的它都有,靜態代理沒有的,它也有;
- 可以使得我們的真實角色更加純粹 . 不再去關注一些公共的事情;
- 公共的業務由代理來完成 . 實現了業務的分工;
- 公共業務發生擴充套件時變得更加集中和方便;
- 一個動態代理 , 一般代理某一類業務;
- 一個動態代理可以代理多個類,代理的是介面!