Spring的动态代理是通过JDK的Proxy类来实现的。Proxy类是Java提供的一个用于创建动态代理对象的工具类,它通过指定的接口数组和InvocationHandler接口来生成一个代理类的实例。
Spring中动态代理的实现步骤如下:
示例代码如下:
public interface UserService {
void addUser(String name);
void deleteUser(String name);
}
public class UserServiceImpl implements UserService {
public void addUser(String name) {
System.out.println("Add user: " + name);
}
public void deleteUser(String name) {
System.out.println("Delete user: " + name);
}
}
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before invoking method: " + method.getName());
Object result = method.invoke(target, args);
System.out.println("After invoking method: " + method.getName());
return result;
}
}
public class Main {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
MyInvocationHandler handler = new MyInvocationHandler(userService);
UserService proxy = (UserService) Proxy.newProxyInstance(
userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(),
handler);
proxy.addUser("Alice");
proxy.deleteUser("Bob");
}
}
输出结果:
Before invoking method: addUser
Add user: Alice
After invoking method: addUser
Before invoking method: deleteUser
Delete user: Bob
After invoking method: deleteUser
以上代码中,定义了一个UserService接口和其实现类UserServiceImpl,MyInvocationHandler是InvocationHandler的实现类,用于处理代理对象的方法调用。在main方法中,使用Proxy.newProxyInstance方法生成了一个代理对象proxy,通过代理对象调用方法时会先调用MyInvocationHandler的invoke方法进行处理。