chatgpt

Spring 的动态代理和 JDK 的动态代理在实现和使用方面有一些关键区别。下面是它们的详细对比:

JDK 动态代理

特点:

  1. 接口代理
  2. 基于反射机制
  3. 实现方式

示例代码:

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();
    }
}

Spring 动态代理

特点:

  1. 两种代理方式
  2. CGLIB 代理
  3. 简化配置

示例代码:

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();
    }
}

总结