CGLIB framework introduction and use tutorial
CGLIB (Code Generation Library) is a powerful byte code generating library that is mainly used to expand the Java class and create dynamic proxy objects during runtime.Compared with Java's standard dynamic proxy (JDK Dynamic Proxy), CGLIB has higher performance, but it is slightly more complicated.
The main features of CGLIB include:
1. Create the proxy object by generating subclasses that generate target class, without having to implement any interface.This method is called Subclass Proxy.It can represent ordinary Java classes, including the Final class.
2. Supporting methods and other functions (MethodinterCePTOR) and callback filter (callbackFilter) can add additional logic before and after the proxy object execution method.
3. The method of proxy by the proxy of the proxy by CGLIB to proxy the target class, so the method of calling the proxy object will be slightly slower than using the original target object.However, once the agent object is generated, the subsequent method call will be very fast.
The following is an example of creating a dynamic proxy object using CGLIB:
First, you need to add the CGLib library to the project's dependence through Maven or other ways.
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.4.0</version>
</dependency>
Then, create an ordinary Java class as the target class:
public class UserService {
public void addUser(String username) {
System.out.println("Adding user: " + username);
}
}
Next, write a method interceptor class to add additional logic before and after the execution of the proxy object method:
public class UserServiceInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("Before method: " + method.getName());
Object result = proxy.invokeSuper(obj, args);
System.out.println("After method: " + method.getName());
return result;
}
}
Finally, use CGLIB dynamically to create proxy objects in the main program:
public class Main {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserService.class);
enhancer.setCallback(new UserServiceInterceptor());
UserService proxy = (UserService) enhancer.create();
proxy.addUser("John");
}
}
In the above code, we use the Enhancer class to create proxy objects, specify the target class and method interceptors.By calling the Create method, CGLIB will generate an agent object for us.When the adduser method of the proxy object is called, the method interceptor will print the log before and after executing.
This is the basic step of creating proxy objects using the CGLIB library.Through the CGLIB framework, we can dynamically modify the behavior of the class to achieve AOP (facing the cut -the -surface programming) and some other advanced functions.