0% found this document useful (0 votes)
4 views

Spring AOP

Spring AOP (Aspect-Oriented Programming) is a feature of the Spring framework that modularizes cross-cutting concerns like logging and security, allowing for cleaner code without altering business logic. It enhances code modularity, reduces duplication, and provides flexibility through aspects, join points, and various types of advice. The document outlines key concepts, benefits, and the operational steps of Spring AOP, including proxy creation and exception handling.

Uploaded by

saddubuddu1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Spring AOP

Spring AOP (Aspect-Oriented Programming) is a feature of the Spring framework that modularizes cross-cutting concerns like logging and security, allowing for cleaner code without altering business logic. It enhances code modularity, reduces duplication, and provides flexibility through aspects, join points, and various types of advice. The document outlines key concepts, benefits, and the operational steps of Spring AOP, including proxy creation and exception handling.

Uploaded by

saddubuddu1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Spring AOP

Guide
LAHIRU
LIYANAPATHIRANA
PAGE 2/29

What is Spring AOP?


Spring AOP (Aspect-Oriented
Programming) is a core feature of the
Spring framework.
It allows modularizing cross-cutting
concerns such as:
logging
security
transaction management
performance monitoring
validating
exception handling etc.
It allows adding more behaviors to the
existing code without modifying the core
business logic.

LAHIRU
LIYANAPATHIRANA
PAGE 3/29

Benefits of Spring AOP


Improve Code Modularity

Isolates cross-cutting concerns from


business logic, creating cleaner, more
maintainable code structures.
Reduce Code Duplication

Centralizes common functionalities,


enabling reuse across multiple application
components.
Enhance Flexibility

Enables easily adding or modifying cross-


cutting concerns without altering core
business logic.
LAHIRU
LIYANAPATHIRANA
PAGE 4/29

Benefits of Spring MVC


Declarative Programming

Supports aspect definition through XML


configurations or annotations (AspectJ
style annotations)
Seamless Spring Integration

Integrates natively with Spring Inversion of


Control (IoC) container, enhancing
component management.

LAHIRU
LIYANAPATHIRANA
PAGE 5/29

Key Concepts of Spring AOP


Following are the key concepts of Spring
AOP:
Aspect
Join Point
Advice
Pointcut
Weaving

LAHIRU
LIYANAPATHIRANA
PAGE 6/29

Aspect
Aspect is a modular unit that encapsulates
a cross-cutting concern. It is a specialized
class that contains logic for a specific
cross-cutting task, such as logging or
transaction management.

In spring, an aspect can be created using


the @Aspect annotation.

Join Point
Join Point is a specific point in program
execution (such as a method call) where
an aspect can be applied.

LAHIRU
LIYANAPATHIRANA
PAGE 7/29

Advice
Advice is an action taken by an Aspect at
a particular Join Point. Spring supports 5
types of Advice:
Before Advice:
Runs before the Join Point.
Can be defined by @Before
annotation.
Example: Log the method name
before execution.
After Advice:
Runs after the Join Point, regardless of its
outcome.
Can be defined by @After annotation.
Example: Release resources like
database connections.
LAHIRU
LIYANAPATHIRANA
PAGE 8/21

Advice
Around Advice:
Wraps the Join Point and allows actions
before and after execution.
Can be defined by @Around
annotation.
Example: Measure execution time.
After Returning Advice:
Runs after a method completes
successfully.
Can be defined by @AfterReturning
annotation.
Example: Log the return value of a
method.

LAHIRU
LIYANAPATHIRANA
PAGE 9/29

Advice
After Throwing Advice:
Runs if the Join Point throws an exception.
Can be defined by @AfterThrowing
annotation.
Example: Log or handle exceptions
consistently.

LAHIRU
LIYANAPATHIRANA
PAGE 10/29

Pointcut
Pointcut is a predicate (or filter)
expression that matches one or more Join
Points where the Advice should be
applied.

Pointcuts can be separately defined using


@Pointcut annotation.

Common Pointcut Expressions in Spring


AOP:
execution: Matches method execution
based on the method's signature.
Example:
execution(* com.example.service.*.*(..))
Matches all methods in service package.

LAHIRU
LIYANAPATHIRANA
PAGE 11/29

Pointcut
within: Matches all methods within a
specified class or package.
Example:
within(com.example.service.*)
args: Matches methods based on
argument types.
Example:
args(String, ..)
Matches methods with the first argument
as a String.
@annotation: Matches methods
annotated with a specific annotation.
Example:
@annotation(org.springframework.transact
ion.annotation.Transactional)
LAHIRU
LIYANAPATHIRANA
PAGE 12/29

Weaving
Weaving is the process of linking Aspects
to target objects.

There are 03 types of weaving:

Runtime Weaving: Done at runtime


using proxies
Load-Time Weaving: Done when
classes are loaded to JVM
Compile-Time Weaving: Done at
compile time

Spring AOP supports Runtime Weaving


leveraging JDK Dynamic Proxies or
CGLIB Proxies.
LAHIRU
LIYANAPATHIRANA
PAGE 13/29

Weaving
JDK Dynamic Proxies:

Used for classes that implement at


least one interface.
Creates a proxy object implementing
the same interface as the target.
Limitation: Only works for interfaces.

CGLIB Proxies:

Used for classes that don’t implement


any interfaces.
Creates a subclass of the target class
and overrides its methods.
Limitation: Cannot proxy final
methods.
LAHIRU
LIYANAPATHIRANA
PAGE 14/29

AspectJ Integration
Even though Spring only supports Runtime
Weaving by default, it can integrate with
AspectJ for more advanced AOP
features.

AspectJ is a comprehensive AOP


framework that supports Runtime,
Compile-Time, and Load-Time weaving.

LAHIRU
LIYANAPATHIRANA
PAGE 15/29

How Spring AOP Works?


Step 1: Define Aspects and Advices

Developers start by creating aspects using


the @Aspect annotation and define
various types of Advices (@Before, @After,
@Around, etc.) along with their pointcut
expressions.

Aspects must be registered as Spring


beans using @Component or similar
annotations.

Pointcuts can be separately defined using


@Pointcut annotation for better
reusability.

LAHIRU
LIYANAPATHIRANA
PAGE 16/29

How Spring AOP Works?


Step 2: Configure Spring AOP

Spring AOP must be enabled using


@EnableAspectJAutoProxy annotation or
equivalent XML configuration.

Developers can configure proxy type,


load-time weaving, and other AOP-
specific settings that affect how proxies
are created and handled.

LAHIRU
LIYANAPATHIRANA
PAGE 17/29

How Spring AOP Works?


Step 3: Spring Container Initialization

When the Spring application context


starts, it performs the initial configuration
processing.

Spring creates bean factory post-


processors, reads all configuration
metadata, and begins scanning for
component/bean definitions.

During this phase, Spring identifies all


classes marked with @Aspect annotation
and validates their configurations,
including pointcut expressions and advice
declarations.
LAHIRU
LIYANAPATHIRANA
PAGE 18/29

How Spring AOP Works?


Step 4: Bean Processing

During bean instantiation, Spring


processes each bean that the container
will manage.

It first creates the target bean instance


and then determines if any Pointcuts
match this bean's methods.

Spring creates a list of applicable Advices


for each matched bean and determines
the appropriate proxy type based on
whether the bean implements interfaces
or configuration settings.

LAHIRU
LIYANAPATHIRANA
PAGE 19/29

How Spring AOP Works?


Step 5: Proxy Creation

Based on the bean analysis, Spring


creates the appropriate type of proxy.

If the target bean implements an


interface, Spring creates a JDK dynamic
proxy implementing the same interfaces.

The following configurations can be used:

@EnableAspectJAutoProxy (default JDK


dynamic proxy)

@EnableAspectJAutoProxy(proxyTarget
Class = false)
LAHIRU
LIYANAPATHIRANA
PAGE 20/29

How Spring AOP Works?


Step 5: Proxy Creation

Otherwise, if there's no interface or


proxyTargetClass=true, Spring creates a
CGLIB proxy by extending the target class.

The following configuration is used:

@EnableAspectJAutoProxy(proxyTarget
Class = false)

These proxies are created during bean


instantiation but before the bean is fully
initialized.

LAHIRU
LIYANAPATHIRANA
PAGE 21/29

How Spring AOP Works?


Step 6: Advice Chain Building

For each proxied method, Spring creates


an ordered chain of method interceptors.

The Advices are sorted based on their


precedence (defined by @Order
annotation or Ordered interface).

This creates a deterministic invocation


chain to be executed when the method is
called.

Spring optimizes this process by caching


the chains for reuse.

LAHIRU
LIYANAPATHIRANA
PAGE 22/29

How Spring AOP Works?


Step 7: Runtime Method Invocation

When a proxied method is called during


runtime, the proxy intercepts the call and
begins executing the advice chain.

The execution follows a specific order:

Before Advice execute


Around Advice starts
Actual method invocation occurs
Around Advice completes
After Advice execute
AfterReturning Advice execute
AfterThrowing Advice executes (if an
exception occurs)
LAHIRU
LIYANAPATHIRANA
PAGE 23/29

How Spring AOP Works?


Step 8: Exception Handling

If an exception occurs during method


execution, the normal advice chain is
interrupted.

Spring then executes any AfterThrowing


advice that matches the exception type,
followed by After (finally) advice.

The exception handling chain works in


reverse order of the normal advice chain,
and each advice handles or modifies the
exception before it propagates to the
caller.

LAHIRU
LIYANAPATHIRANA
PAGE 24/29

How Spring AOP Works?


Step 9: Method Return

Upon method completion, Spring


processes the return value through any
remaining Advices in the chain. Around
and AfterReturning advice can modify the
return value if needed.

The proxy ensures type compatibility and


handles any necessary proxy unwrapping
before returning the final result to the
caller.

After Advices are guaranteed to execute


even if exceptions occur during method
execution.
LAHIRU
LIYANAPATHIRANA
PAGE 25/29

How Spring AOP Works?


Step 10: Proxy Behavior and
Optimization

Throughout the entire process, Spring


manages proxy behavior including
handling of target object state, thread
safety, and identity.

It optimizes performance by caching proxy


instances, pointcut matching results, and
advice chains.

AOP framework also ensures proper


cleanup of resources when needed.

LAHIRU
LIYANAPATHIRANA
PAGE 26/29

How Spring AOP Works?


Step 10: Proxy Behavior and
Optimization

Throughout the entire process, Spring


manages proxy behavior including
handling of target object state, thread
safety, and identity.

It optimizes performance by caching proxy


instances, pointcut matching results, and
advice chains.

AOP framework also handles special


cases like self-invocation and ensures
proper cleanup of resources when
needed.
LAHIRU
LIYANAPATHIRANA
PAGE 27/29

Spring AOP Do’s And Don’ts


✅ Do
Use AOP for cross-cutting tasks like logging
and security

Keep aspects simple and focused on one


task and stateless

Use interfaces to enable JDK dynamic


proxies for better performance

Write specific and focused pointcut


expressions instead of broad patterns

Always create objects that need AOP


through the Spring container

LAHIRU
LIYANAPATHIRANA
PAGE 28/29

Spring AOP Do’s And Don’ts


❌ Don't
Don't use AOP for core business logic
implementation

Don't try to intercept private/protected


methods or field access - Spring AOP only
works with public methods

Don't make classes or methods final when


using CGLIB proxies

Don't create objects using the 'new'


operator for objects needing AOP

Don't use complex pointcut expressions


which lead to performance impacts
LAHIRU
LIYANAPATHIRANA
PAGE 7/7

Did You Find This


Post Useful?

Stay Tuned for More


Spring Related Posts
Like This

LAHIRU
LIYANAPATHIRANA

You might also like