Skip to content

Spring AOP Introduction#

What Is The Aspect Oriented Programming (AOP)?#

  • Aspect-oriented Programming (AOP) complements Object-oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns (such as transaction management) that cut across multiple types and objects. (Such concerns are often termed "crosscutting" concerns in AOP literature.)

  • One of the key components of Spring is the AOP framework. While the Spring IoC container does not depend on AOP (meaning you do not need to use AOP if you don’t want to), AOP complements Spring IoC to provide a very capable middleware solution.

  • More information

  • So let's take an example about a business problem then we can understand it easier. Let's image that we need to add logging to our Spring Boot project before starting of every methods. So Let's image that we have a lot of methods in our Spring Boot project in many layers. So the developer may have to do it manually and will take many efforts and time.

  • Then let's think about updating the logging message. If we applied for 100 classed then when we want to update the logging message then we have to update all classes. It is painful for developers. So at this point Aspect-Oriented Programming (AOP) will handle issues above.

AOP Concepts#

  • There are some central AOP concepts and terminology defined in the table as below.
Term Description
Aspect A modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented by using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).
Join point A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
Advice Action taken by an aspect at a particular join point. Different types of advice include "around", "before", and "after" advice. (Advice types are discussed later.) Many AOP frameworks, including Spring, model an advice as an interceptor and maintain a chain of interceptors around the join point.
Pointcut A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.
Introduction Declaring additional methods or fields on behalf of a type. Spring AOP lets you introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)
Target object An object being advised by one or more aspects. Also referred to as the "advised object". Since Spring AOP is implemented by using runtime proxies, this object is always a proxied object.
AOP proxy An object created by the AOP framework in order to implement the aspect contracts (advice method executions and so on). In the Spring Framework, an AOP proxy is a JDK dynamic proxy or a CGLIB proxy.
Weaving Linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
  • Spring AOP includes the following types of advice.
Advice Type Description
Before advice Advice that runs before a join point but that does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
After returning advice Advice to be run after a join point completes normally (for example, if a method returns without throwing an exception).
After throwing advice Advice to be run if a method exits by throwing an exception.
After (finally) advice Advice to be run regardless of the means by which a join point exits (normal or exceptional return).
Around advice Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Benefit Of AOP#

  • Reusable Aspects: AOP allows the encapsulation of cross-cutting concerns into reusable modules or classes (aspects).
  • Configuration-Based Application: Aspects can be applied selectively to different parts of the project based on configuration.
  • Cross-Cutting Logic Encapsulation: AOP helps in encapsulating common logic, making it easier to manage and maintain.
  • Cleaner Business Code: Business-specific code remains focused on core functionalities, reducing complexity.

AOP Use Cases#

  • Exception handling: log exception and notify DevOps team via SMS/email
  • Api Management: how many times has a method been called user, analytics: what are peak times? what is average load? who is top user?
    • Common Use Cases: Logging, security, and transactions are common AOP use cases.
    • Additional Use Cases: AOP can be used for audit logging, exception handling, API management, and other cross-cutting concerns.

AOP Advantages#

  • Reusable Modules: Aspects serve as reusable modules to encapsulate cross-cutting concerns.
  • Code Tangling and Scattering Resolution: Addresses issues of code tangling and scattering.
  • Selective Application: Aspects can be applied selectively based on configuration.

AOP Disavantages#

  • Complexity with Too Many Aspects: If there are too many aspects, the application flow can become hard to follow. Governance and moderation in aspect development are essential.
  • Minor Performance Impact: Runtime weaving, used by Spring AOP, may have a minor performance impact. Overusing aspects with expensive operations can magnify this impact.

AOP Frameworks#

  • Spring AOP:

    • Support: Provides AOP support out of the box.
    • Usage in Spring: Used in the background for security, transactions, and caching in the Spring framework.
    • Weaving Approach: Utilizes run-time weaving of aspects using the proxy pattern.
  • AspectJ:

    • Original Framework: Released in 2001.
    • Support for Full AOP Spec: Offers complete support for the full AOP stack.
    • Rich Support: Provides rich support for join points, including method, constructor, and field-level join points.
    • Code Weaving: Supports compile-time, post compile-time, and load-time weaving.
  • Performance Considerations::

    • Spring AOP: Uses run-time weaving, which may have a minor performance impact.
    • AspectJ: Provides various weaving options, allowing developers to choose based on their performance requirements.

Spring AOP And AspectJ Comparing#

  • Spring AOP:
Advantages: Disadvantages:
Simpler to use than AspectJ. Supports only method-level join points.
Makes use of the Proxy pattern. Aspects can be applied only to beans created by the Spring app context.
Easy migration to AspectJ using the @Aspect annotations. Minor performance cost for aspect execution due to run-time weaving.
  • AspectJ:
Advantages: Disadvantages:
Supports all join points, including method-level, constructor, and field. Requires an extra compilation step for compile-time weaving.
Works with any POJO, not limited to Spring beans. AspectJ pointcut syntax can become complex quickly.
Faster performance compared to Spring AOP.
Complete AOP support with a full stack and API.
  • Terms comparison.
Term Spring AOP AspectJ
Join Points Method-level All (method, constructor, field)
Weaving Run-time Compile-time, post compile-time, and load-time
Complexity Lightweight, addresses common enterprise application problems Fast but can be complex, suitable for advanced requirements

Recommendation#

  • Start with Spring AOP for its simplicity and ease of understanding.
  • Move to AspectJ if you have complex requirements beyond the capabilities of Spring AOP.

References#