Mastering CGLIB Dynamic Proxies in Java: A Hands‑On Guide
This tutorial explains how to use CGLIB to create Java dynamic proxies, compares it with JDK proxies, shows step‑by‑step code examples, and demonstrates how to inspect generated classes via decompilation.
CGLIB (Code Generation Library) is an open‑source, high‑performance library that generates bytecode at runtime, allowing Java classes to be extended or interfaces to be implemented dynamically. It powers frameworks like Hibernate and Spring AOP by using ASM under the hood.
CGLIB Introduction
CGLIB leverages the ASM bytecode manipulation framework to create new classes on the fly, but developers are discouraged from using ASM directly due to its complexity.
Getting Started
Add the CGLIB dependency to your project:
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.5</version>
</dependency>Define a simple target class, UserDao, with methods to query users:
public class UserDao {
public void findAllUsers(){
System.out.println("UserDao 查询所有用户");
}
public String findUsernameById(int id){
System.out.println("UserDao 根据ID查询用户");
return "公众号:程序新视界";
}
}Create a method interceptor by implementing net.sf.cglib.proxy.MethodInterceptor:
public class LogInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
before(method.getName());
Object result = proxy.invokeSuper(obj, args);
after(method.getName());
return result;
}
private void before(String name){ System.out.println("调用方法"+name+"之【前】的日志处理"); }
private void after(String name){ System.out.println("调用方法"+name+"之【后】的日志处理"); }
}The interceptor receives the target object, the method being called, its arguments, and a MethodProxy that can invoke the original implementation.
Client Usage
public class CglibTest {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserDao.class);
enhancer.setCallback(new LogInterceptor());
UserDao userDao = (UserDao) enhancer.create();
userDao.findAllUsers();
userDao.findUsernameById(1);
}
}Running the program prints log messages before and after each method call, confirming that the proxy adds the desired behavior.
Saving Generated Classes
To inspect the generated proxy class, set the system property:
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "/Users/zzs/temp");This writes three class files to the specified directory, which can be decompiled to reveal the bytecode structure.
CGLIB Proxy Creation Process
Identify all non‑final public methods of the target class.
Convert eligible method definitions into bytecode.
Load the generated bytecode as a new proxy class.
Implement MethodInterceptor to handle method invocations.
JDK Proxy vs. CGLIB
JDK dynamic proxies rely on Java reflection and require the target class to implement an interface. CGLIB creates a subclass of the target class using ASM, avoiding the need for interfaces and offering higher performance.
Advantages of JDK proxies include minimal dependencies, simplicity, and native support across Java versions. CGLIB’s strengths are non‑intrusive proxying (no interface needed) and better performance.
Conclusion
Both proxy mechanisms have trade‑offs; Spring often chooses CGLIB for features that need class‑based proxying. Understanding the generation steps and how to inspect the resulting classes helps developers make informed decisions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
