1. 代理设计模式
代理设计模式主要对我们的方法前后实现增强。
2. 应用场景
- 打印日志
- Aop和事务Aop
- Mybatis中 mapper接口
- 全局捕获异常
- Lcn、seata、分表分框架shadingjdbc 代理数据源
- 自定义注解生效(反射技术+Aop)
- Rpc远程调用技术代理设计模式
3.代理类优缺点
优点:实现扩展功能,对我们方法实现增强、安全性、冗余性提高代码复用机制。
缺点:生成非常多代理的class文件。
4. jdk动态代理
package com.tostyle.jdk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author tostyle
* 2022/4/6 15:05
*/
public class JdkInvocationHandler implements InvocationHandler {
private Object target;
public JdkInvocationHandler(Object o){
this.target=o;
}
/**
* 使用生成代理拦截回调
* @param proxy 动态生成的代理类
* @param method 接口中的方法
* @param args 代理类参数
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("jdk动态代理开始");
//调用目标方法 java的反射
Object invoke = method.invoke(target, args);
System.out.println("jdk动态代理结束");
return invoke;
}
/**
* 使用jdk创建代理类对象
* @param <T>
* @return
*/
public <T> T getProxy(){
//ClassLoader 读取代理类的class文件
//interfaces 基于该接口拼接代理类的源代码
//InvocationHandler this
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
}
package com.tostyle.proxy.inter;
/**
* @author tostyle
* 2022/4/6 10:14
*/
public interface BookService {
/**
* 需要被代理的方法
* @param bookName
* @return
*/
String addBook(String bookName);
}
package com.tostyle.proxy.inter;
/**
* @author tostyle
* 2022/4/6 13:49
*/
public class BookServiceImpl implements BookService{
@Override
public String addBook(String bookName) {
System.out.println("tostyle"+bookName);
return "tostyle"+bookName;
}
}
5. 测试
package com.tostyle.reflect;
import com.tostyle.jdk.JdkInvocationHandler;
import com.tostyle.proxy.inter.BookService;
import com.tostyle.proxy.inter.BookServiceImpl;
/**
* @author tostyle
* 2022/4/6 15:15
*/
public class ProxyTest002 {
public static void main(String[] args) {
JdkInvocationHandler jdkInvocationHandler = new JdkInvocationHandler(new BookServiceImpl());
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
BookService proxy = jdkInvocationHandler.getProxy();
String addBook = proxy.addBook("测试JDK代理类");
}
}