1.静态代理
静态代理缺点:
①.每次代理都要实现一个类,导致项目中代码很多;
②.代码都是写死的,一个代理只能实现固定的功能,无法灵活多变
1.继承方式实现代理(静态代理中的继承代理)
//目标对象
public class UserImpl {
public void query(String name) {
System.out.println("query name = " + name);
}
}
//代理对象
public class LogUserProxy extends UserImpl{
public void query(String name) {
System.out.println("log ...");
System.out.println("query name = " + name);
}
}
//测试类
public class Main {
public static void main(String[] args) {
//父类指向子类
UserImpl user = new LogUserProxy();
user.query("张三");
}
}
代理对象实现了对目标对象的增强,但只能增强一次。
2.聚合方式实现代理
//抽象对象
public interface UserService {
public void query(String name);
}
//目标对象
public class UserImpl implements UserService {
public void query(String name) {
System.out.println("query name = " + name);
}
}
//代理对象1
public class LogUserProxy implements UserService {
private UserService userService;
public LogUserProxy(UserService userService) {
this.userService = userService;
}
public void query(String name) {
System.out.println("log ...");
userService.query(name);
}
}
//代理对象2
public class TimeUserProxy implements UserService {
private UserService userService;
public TimeUserProxy(UserService user) {
this.userService = user;
}
public void query(String name) {
System.out.println("time ...");
userService.query(name);
}
}
public class Main {
public static void main(String[] args) {
UserService user = new UserImpl();
UserService logUser = new LogUserProxy(user);
UserService timeUser = new TimeUserProxy(logUser);
timeUser.query("张三");
}
}
输出结果:
time ...
log ...
query name = 张三
代理对象1和代理对象2对目标对象实现了两次增强。聚合代理方式可以实现多次增强。
2.动态代理
动态代理有JDK的动态代理和cglib的动态代理,例如Spring Boot中就使用了这两种代理方式,默认使用JDK的代理方式,当类没有实现接口时使用cglib的动态代理。
Spring Boot动态代理参考文章 https://www.jianshu.com/p/8cd3b352ab38
下面介绍JDK的动态代理
下面代码类似JDK框架的动态代理,主要作用是生成一个临时实现类。通过此代码可以了解JDK动态代理的思想
package com.tomorrowsg.test.util;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class ProxyUtil {
public static Object newProxyInstance(Object target) throws Exception{
String content = "";
String packageContent = "package com.test;";
Class targetInfo = target.getClass().getInterfaces()[0];
String targetInfoName = targetInfo.getSimpleName();
String importContent = "import " + targetInfo.getName() + ";";
String classContent = "public class $Proxy implements " + targetInfoName + "{";
String fieldContent = "private " + targetInfoName + " target;";
String construterContent = "public $Proxy(" + targetInfoName + " target){"
+"this.target = target;}";
String methodsContent = "";
Method[] methods = targetInfo.getDeclaredMethods();
for (Method method : methods) {
String methodName = method.getName();
Class returnType = method.getReturnType();
Class<?>[] parameterTypes = method.getParameterTypes();
String argsContent = "";
String argsNames = "";
int i = 0;
for (Class<?> parameterType : parameterTypes) {
String simpleName = parameterType.getSimpleName();
argsContent+= simpleName + " p" + i + ",";
argsNames+="p" + i + ",";
i++;
}
if (argsContent.length() > 0) {
argsContent = argsContent.substring(0, argsContent.lastIndexOf(",")-1);
argsNames = argsNames.substring(0, argsNames.lastIndexOf(",")-1);
}
methodsContent += "public " + returnType + " " + methodName + "(" + argsContent+"){"
+"System.out.println(\"log...\");"
+"target." + methodName + "(" + argsNames + ");}";
}
content += packageContent + importContent + classContent + fieldContent + construterContent + methodsContent + "}";
File file = new File("D:\\com\\test\\$Proxy.java");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.flush();
fileWriter.close();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable units = fileManager.getJavaFileObjects(file);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, units);
task.call();
fileManager.close();
URL[] urls = new URL[]{new URL("file:D:\\\\")};
URLClassLoader urlClassLoader = new URLClassLoader(urls);
Class clazz = urlClassLoader.loadClass("com.test.$Proxy");
Constructor constructor = clazz.getConstructor(targetInfo);
Object proxy = constructor.newInstance(target);
return proxy;
}
}
上面代码的作用是在磁盘上生成一个类似如下代码的一个代理类,并自动完成编译、装载并返回一个实例化对象。此种方式生成的代理类更具灵活性,可以重用。
public class LogUserProxy implements UserService {
private UserService userService;
public LogUserProxy(UserService userService) {
this.userService = userService;
}
public void query(String name) {
System.out.println("log ...");
userService.query(name);
}
}
public class Main {
public static void main(String[] args) throws Exception {
UserService user = new UserImpl();
UserService proxy = (UserService) ProxyUtil.newProxyInstance(user);
proxy.query("张三");
}
}
输出结果如下
log...
query name = 张三