How is dynamic proxy implemented in Spring?

Spring’s dynamic proxy is implemented through the JDK’s Proxy class. Proxy class is a utility class provided by Java for creating dynamic proxy objects, generating an instance of a proxy class through a specified interface array and InvocationHandler interface.

The implementation steps of Spring dynamic proxy are as follows:

  1. Create a class that implements the InvocationHandler interface, and within this class implement the invoke method, which serves as the handler for when a method is executed on the proxy object.
  2. Generate a proxy object by using the newProxyInstance method of the Proxy class, passing in a ClassLoader, an array of interfaces, and an implementation class object of the InvocationHandler.
  3. When a method is called using a proxy object, the invoke method in the InvocationHandler will be called first for processing.

The example code is as follows:

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

The output result:

Before invoking method: addUser
Add user: Alice
After invoking method: addUser
Before invoking method: deleteUser
Delete user: Bob
After invoking method: deleteUser

In the above code, a UserService interface and its implementation class UserServiceImpl are defined. MyInvocationHandler is a subclass of InvocationHandler used to handle method calls on proxy objects. In the main method, a proxy object is created using the Proxy.newProxyInstance method, and when methods are called on the proxy object, the invoke method of MyInvocationHandler is first invoked for processing.

bannerAds