chatgpt
Spring 的动态代理和 JDK 的动态代理在实现和使用方面有一些关键区别。下面是它们的详细对比:
java.lang.reflect.Proxy
类和 InvocationHandler
接口。InvocationHandler
接口来定义代理类的行为。Proxy.newProxyInstance()
方法创建代理实例。import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKDynamicProxyExample {
public interface Service {
void perform();
}
public static class ServiceImpl implements Service {
public void perform() {
System.out.println("Service is performing.");
}
}
public static class ServiceInvocationHandler implements InvocationHandler {
private final Service service;
public ServiceInvocationHandler(Service service) {
this.service = service;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method invocation");
Object result = method.invoke(service, args);
System.out.println("After method invocation");
return result;
}
}
public static void main(String[] args) {
Service service = new ServiceImpl();
Service proxyInstance = (Service) Proxy.newProxyInstance(
service.getClass().getClassLoader(),
service.getClass().getInterfaces(),
new ServiceInvocationHandler(service)
);
proxyInstance.perform();
}
}
final
。ProxyFactory
或通过配置文件和注解(如 @Transactional
, @Aspect
)来配置代理,简化了代理的使用。import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class SpringDynamicProxyExample {
public static class Service {
public void perform() {
System.out.println("Service is performing.");
}
}
public static class BeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("Before method invocation");
}
}
public static void main(String[] args) {
Service target = new Service();
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(target);
proxyFactory.addAdvice(new BeforeAdvice());
Service proxy = (Service) proxyFactory.getProxy();
proxy.perform();
}
}
InvocationHandler
接口和 Proxy
类。ProxyFactory
,以及通过配置文件和注解简化代理的创建。