Spring Boot HandBook

    Spring Proxy and Internal working of AOP

    Introduction#

    Spring Proxy and AOP (Aspect-Oriented Programming) in Spring enable the separation of cross-cutting concerns (like logging or transactions) from business logic. Spring uses proxies (JDK dynamic proxies or CGLIB) to intercept method calls, applying additional behavior without modifying the core logic.

    AOP works by defining Aspects (reusable functionalities) that apply to Join Points (method executions). The Advice (actions like @Before, @After, or @Around) is linked to these points through Pointcuts, which define where the advice should be applied. Weaving applies aspects to target objects, typically at runtime, creating cleaner and more modular code.

    How Proxies are managed?#

    • Stored in the ApplicationContext:
      • The proxy replaces the actual bean in the Spring container (ApplicationContext or BeanFactory).
      • Any request for the bean (via @Autowired, @Resource, getBean(), etc.) returns the proxy.
    • Behavior Wrapping:
      • The proxy wraps the original bean, intercepting method calls.
      • Additional behavior (advice) is executed before and/or after delegating to the original method.
    • Transparent to Clients:
      • For the client, the proxy behaves like the original bean.
      • The client interacts with the proxy as if it were the actual bean, without being aware of the proxying mechanism.
    • Proxy Lifecycle:
      • The proxy lifecycle is tied to the original bean's lifecycle.
      • Destroying the proxy also destroys the underlying bean.

    The proxy in Spring is like a library assistant who acts as an intermediary between you and rare books. The assistant ensures rules are followed (like wearing gloves) before and after handling the book, just as a Spring proxy adds behaviors (like logging or security) around method calls. You interact with the assistant as if they were the librarian, without noticing the proxy's management. Both the assistant and the book are tied to the library's lifecycle, just like proxies and beans in Spring.

    How Proxy are created?#

    1. Spring's Decision to Proxy:
      • During the initialization of the application context, Spring examines beans to determine if they require proxying.
      • Proxying is triggered by specific configurations or annotations:
        • AOP: @Aspect, @Around, etc.
        • Transactions: @Transactional
        • Caching: @Cacheable, @CacheEvict
      • If a bean matches the criteria for proxying, Spring creates a proxy instead of the actual bean.
    2. Proxy Mechanisms:
      • JDK Dynamic Proxies: Used when the target object implements one or more interfaces.
        • Proxy implements the same interfaces as the target.
      • CGLIB Proxies: Used when the target object does not implement any interfaces.
        • Proxy subclass inherits from the target class and overrides its methods.
    3. Proxy Object Creation:
      • The proxy is created during the bean post-processing phase, typically by a BeanPostProcessor like ProxyFactoryBean or AnnotationAwareAspectJAutoProxyCreator.

    In the analogy, creating proxies in Spring is like setting up security guards for a building. Spring decides to "proxy" beans if they need special handling, like transactions or caching (like assigning guards to restricted areas). The type of proxy depends on whether the bean implements interfaces (JDK proxy) or not (CGLIB proxy). Proxies are created during the setup phase, just like guards are stationed before the building opens, ensuring everything operates securely.

    How Proxies are used?#

    1. Spring Scans for Advice (Setting Up the Security Plan)#

    Before the building opens, the security manager (Spring) reviews the building’s security plan. They identify areas where special attention is needed (like restricted zones) and set rules (like logging in and out or scanning bags) for each area.

    Spring’s Mechanism:#

    • Spring scans the classes for aspects and determines which beans need advice (e.g., @Transactional, @Cacheable, @Aspect).
    • Based on this, Spring creates a security plan (pointcuts) and applies the advice to the relevant beans.

    2. Deciding if Proxying Is Needed (Identifying Restricted Areas)#

    The security manager identifies which areas require guards. If an area has a special security protocol (like the CEO’s office), a guard will be assigned.

    Spring’s Mechanism:#

    • Spring checks each bean to determine if any methods match a pointcut (specific conditions requiring proxying).
    • If necessary, Spring decides to proxy the bean.

    3. Creating the Proxy (Stationing the Guard)#

    Once the areas that need guards are identified, the security manager assigns a guard (proxy) to each restricted area (target bean).

    Spring’s Mechanism:#

    • Spring creates a proxy object to wrap around the original bean.
    • The proxy will handle incoming requests and apply any advice when necessary.

    4. Intercepting Method Calls (Guard Checks Visitors)#

    When someone approaches a restricted area, the guard intercepts them. The guard checks if any special rules should be applied (like verifying IDs or checking bags).

    Spring’s Mechanism:#

    • When a client calls a method on the proxied bean, the proxy intercepts the call.
    • The proxy checks if the method matches any pointcut (advice) and determines if any advice should be applied.

    5. Delegating to Target Bean (Allowing Entry)#

    If the visitor doesn’t need special screening, the guard lets them pass without any extra checks, allowing them to enter the restricted area.

    Spring’s Mechanism:#

    • If no advice matches, the proxy delegates the call directly to the original bean, allowing the method to be executed without any additional behavior.

    6. Applying Advice (Executing the Security Protocols)#

    If the visitor needs special handling (like logging in or being escorted), the guard executes the required protocol before or after the visitor enters.

    Spring’s Mechanism:#

    • If the pointcut matches, the proxy executes the advice (e.g., logging, transaction management) before, after, or around the original method invocation.

    7. @Around Advice (Most Powerful Guard)#

    The guard at the most secure area (like the CEO’s office) has the power to control the visitor's entry. They can choose to delay the visitor, apply extra checks, or even refuse entry altogether.

    Spring’s Mechanism:#

    • The @Around advice is the most powerful, allowing you to control method execution.
    • You can execute code before or after the method or even skip it entirely using ProceedingJoinPoint.proceed().

    8. Returning Control to the Original Method (Allowing Visitor Inside)#

    After completing the security checks, the guard allows the visitor to proceed into the restricted area.

    Spring’s Mechanism:#

    • After the advice is executed, control returns to the original method.
    • The original method is invoked and the result is returned.

    9. Returning Results or Exceptions (Guard Returns the Outcome)#

    Once the visitor enters, they either successfully complete their visit or are escorted out if something goes wrong.

    Spring’s Mechanism:#

    • The method either returns the result or throws an exception.
    • The proxy passes the result or exception back to the client.

    Weaving#

    Weaving is like adding security checks (aspects) at different points in the building's lifecycle — during the design phase, before opening, or even while the building is in use.

    Types of Weaving:

    • Compile-time Weaving: Security is planned and integrated into the building’s blueprints before it opens (like aspects being woven into the class during compilation).
    • Load-time Weaving: Security measures are activated as the building starts its operations (like aspects being woven when the class is loaded into the JVM).
    • Post-compilation Weaving: Extra security is installed after the building has been operating for some time (like aspects being added after compilation but before execution).

    Spring AOP and Weaving:#

    While Spring primarily uses dynamic proxies (like assigning temporary guards to certain areas of the building), AspectJ integration allows for more advanced weaving, such as compile-time or load-time weaving, for more complex security protocols (aspects).

    Benefits of Proxying in Spring:#

    • Cross-cutting Concerns: Easily handle concerns like logging, security, and transactions.
    • Decoupled Design: Separation of core business logic and additional behaviors.
    • Dynamic Interception: Intercept and modify behavior at runtime.

    Proxy with @Transactional#

    1. When a bean method annotated with @Transactional is called:
      • The proxy intercepts the method call.
      • Starts a transaction (via advice added by Spring's TransactionInterceptor).
      • Delegates the method call to the original bean.
      • Commits or rolls back the transaction after method execution.
    2. The client only interacts with the proxy but perceives it as the actual bean.

    Conclusion#

    This article explains how Spring Proxy and AOP separate cross-cutting concerns like logging and security from core business logic. It covers the creation, usage, and lifecycle of proxies, emphasizing their role in enhancing dynamic behavior without altering the underlying logic. The benefits include decoupling design, dynamic interception, and more maintainable, scalable code.

    Last updated on Jan 14, 2025