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方法進行處理。