Skip to main content
Advertisement

8.3 CGLIB vs JDK Dynamic Proxy Mechanism

Spring AOP inherently abandons the heavy approach of destructively manipulating raw bytecode during code compilation (AspectJ Native Weaver). Instead, it adopts Proxy-based AOP, dynamically wrapping targets by generating intermediary (Proxy) objects safely within the runtime runtime environment.

Technologically, two conflicting concrete implementations exist for generating these memory proxies.

1. JDK Dynamic Proxy

It transparently leverages Java's native core Reflection API to generate raw proxy interfaces. This methodology operationalizes SOLELY when the Target object forcefully implements at least one or more Interface signatures.

  • Pros: Because it utilizes built-in Java standard technologies, it possesses zero dependency on external third-party operational libraries.
  • Cons: You cannot forcibly cast the Proxy down to a concrete class (Instance implementation) type. Consequently, you must absolutely receive Dependency Injection (DI) structured 100% strictly via Interface typing schemas.

2. CGLIB (Code Generation Library)

CGLIB is a versatile external bytecode manipulation library that empowers generating runtime proxies even against generic skeletal concrete classes blindly lacking interface specifications. (It is already bundled internally inside the Spring Core framework distributions). CGLIB parses the Target class and organically derives an in-memory proxy subclass by aggressively inheriting (EXTENDING) the Target class and subsequently overriding its methods verbatim.

  • Pros: Grants profoundly flexible development velocity as it inherently bypasses the rigid necessity of cumbersome interface design restrictions.
  • Cons: If the rigid Target class is sealed tightly as final, or if integral Target methods are blocked by private or final modifiers, standard Java inheritance and overriding become physically impossible. Therefore, Proxy AOP logic cannot functionally penetrate those segments.
Spring Boot's Ingenious Default Strategy

Beginning drastically from Spring Boot 2.0, the framework unilaterally adopted a paradigm aggressively enforcing CGLIB proxy generation regardless of whether the Target object implements an interface (spring.aop.proxy-target-class=true) as the definitive Default value. This behaves as a profound architectural safeguard proactively silencing human-error driven casting outages traditionally inflicted drastically by JDK Dynamic Proxy interface class casting ambiguities natively at the framework frontier.

Advertisement