Spring 动态代理实现
时间: 2024-05-10 14:14:36 浏览: 111
Spring动态代理是通过JDK动态代理和CGLIB动态代理两种方式来实现的。
1. JDK动态代理
JDK动态代理是利用Java反射机制在运行时创建一个实现某一接口的代理类对象。在Spring中,当一个目标类实现了至少一个接口时,默认采用JDK动态代理。JDK动态代理只能代理实现了接口的类,而不能代理没有实现接口的类。
示例代码:
```
public interface UserService {
void addUser();
}
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("add user");
}
}
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before invoke method...");
Object result = method.invoke(target, args);
System.out.println("after invoke method...");
return result;
}
}
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
InvocationHandler invocationHandler = new MyInvocationHandler(userService);
UserService proxy = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(), invocationHandler);
proxy.addUser();
}
```
2. CGLIB动态代理
CGLIB动态代理是通过继承目标类,生成目标类的子类来实现代理。在Spring中,当一个目标类没有实现任何接口时,采用CGLIB动态代理。CGLIB动态代理需要依赖于CGLIB库,可以在运行时动态生成代理类字节码,并加载到JVM中。
示例代码:
```
public class UserService {
public void addUser() {
System.out.println("add user");
}
}
public class MyMethodInterceptor implements MethodInterceptor {
private Object target;
public MyMethodInterceptor(Object target) {
this.target = target;
}
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("before invoke method...");
Object result = proxy.invokeSuper(obj, args);
System.out.println("after invoke method...");
return result;
}
}
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserService.class);
enhancer.setCallback(new MyMethodInterceptor(new UserService()));
UserService userService = (UserService) enhancer.create();
userService.addUser();
}
```
阅读全文