Proxying classes using Decorator pattern in Spring

AAccording to GOF book, Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. This pattern allows you to add and remove behaviors to an individual object at the runtime dynamically or statically without changing the existing behavior of other associated objects from the same class.

In Spring AOP, CGLIB is used to create the proxy in the application. CGLIB proxying works by generating a subclass of the target class at runtime. Spring configures this generated subclass to delegate method calls to the original target--the subclass is used to implement the Decorator pattern, weaving in the advice.

Spring provides two ways to create the proxy in the application.

  • CGLIB proxy
  • JDK proxy or dynamic proxy

Let's see the following table:

Let's see the following figure:

Note--CGLIB proxying has one issue to be considered, that is, final methods can't be advised, as they can't be overridden.

In the following section let's learn more about the cross-cutting concerns.