Spring AOP
Spring AOP
Guide
LAHIRU
LIYANAPATHIRANA
PAGE 2/29
LAHIRU
LIYANAPATHIRANA
PAGE 3/29
LAHIRU
LIYANAPATHIRANA
PAGE 5/29
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.
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.
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.
Weaving
JDK Dynamic Proxies:
CGLIB Proxies:
AspectJ Integration
Even though Spring only supports Runtime
Weaving by default, it can integrate with
AspectJ for more advanced AOP
features.
LAHIRU
LIYANAPATHIRANA
PAGE 15/29
LAHIRU
LIYANAPATHIRANA
PAGE 16/29
LAHIRU
LIYANAPATHIRANA
PAGE 17/29
LAHIRU
LIYANAPATHIRANA
PAGE 19/29
@EnableAspectJAutoProxy(proxyTarget
Class = false)
LAHIRU
LIYANAPATHIRANA
PAGE 20/29
@EnableAspectJAutoProxy(proxyTarget
Class = false)
LAHIRU
LIYANAPATHIRANA
PAGE 21/29
LAHIRU
LIYANAPATHIRANA
PAGE 22/29
LAHIRU
LIYANAPATHIRANA
PAGE 24/29
LAHIRU
LIYANAPATHIRANA
PAGE 26/29
LAHIRU
LIYANAPATHIRANA
PAGE 28/29
LAHIRU
LIYANAPATHIRANA