Three implementations of Java proxy
The Java proxy mode can be implemented in the following ways:
1. Static proxy.
2. JDK dynamic agent.
3. Cglib dynamic agent.
Example, there is an interface to say hello. There are two implementations, say hello and shake hands. The code is as follows.
Interface:
Implementation class:
Without changing the code, you want to do something else before and after executing the target method. It can be implemented by proxy.
1. Static agent. You need to create a proxy class. The proxy class implements the same interface as the target class, the proxy class receives the target class object, and implements the method of calling the target class in the implementation method. As follows:
Test call:
This method has disadvantages. If n interface implementation classes need to be proxied, n proxy classes need to be created.
2. JDK dynamic agent
Create a proxy class as follows:
Compared with the first method, this method does not need to create many proxy classes,
However, it relies on "the proxied object needs to implement the interface", that is, in the code example given above, the dynamic proxy can proxy sayhello and Shakehands, but not kisshelo. Because kisshollo does not implement the interface.
3. Cglib dynamic agent.
To create a proxy class:
Call example:
To sum up, cglib dynamic agent is the best, and the spring framework also uses cglib package.