动态代理
动态代理和静态代理角色一样
动态代理类是动态生成的,不是我们直接写好的。
动态代理分为两大类:
基于接口的动态代理:JDK动态代理【我们在这里使用】
基于类的动态代理:cglib
java字节码:javasist (Jboss服务器)
需要了解2个类:Proxy 代理,invocationHandler 反射包下reflect
实体类:
/**
* @author LongXi
* @create 2021-05-30 10:01
*/
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
/**
* @author LongXi
* @create 2021-05-30 10:00
*/
public interface Rent {
public void rent();
}
代理类接口
/**
* @author LongXi
* @create 2021-05-30 12:58
*/
//我们会用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Rent rent;
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
this.seeHouse();
//动态代理的本质,就是使用反射机制实现
Object result = method.invoke(rent, args);
this.fare();
return result;
}
public void setRent(Rent rent) {
this.rent = rent;
}
public void seeHouse(){
System.out.println("中介带看房子");
}
private void fare(){
System.out.println("收中介费");
}
}
客户类
/**
* @author LongXi
* @create 2021-05-30 13:07
*/
public class Client {
public static void main(String[] args) {
//真是角色
Host host = new Host();
//代理角色,现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setRent(host);
//这个proxy就是动态生成的,我们并没有写
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
测试
改造Demo2
追加代理接口
/**
* @author LongXi
* @create 2021-05-30 12:58
*/
//我们会用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object 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());
//动态代理的本质,就是使用反射机制实现
Object result = method.invoke(target, args);
return result;
}
public void setTarget(Object target) {
this.target = target;
}
public void log(String msg){
System.out.println("执行了"+ msg + "方法");
}
}
客户类
/**
* @author LongXi
* @create 2021-05-30 13:23
*/
public class Client {
public static void main(String[] args) {
//真是角色
UserServiceImpl userService =new UserServiceImpl();
//代理角色不存在
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
proxyInvocationHandler.setTarget(userService);
//动态生成代理类
UserService proxy = (UserService) proxyInvocationHandler.getProxy();
proxy.add();
proxy.delete();
}
}
测试
动态代理的好处:
静态代理的好处全都有
一个动态代理类,代理的是一个接口,一般就是对应的一类业务
一个动态代理类,可以代理多个类,只要实现了同一个接口即可。