01
Spring Boot
Tutorial -
Spring Boot
with AOP
02
Table of Content
Aspect-Oriented Programming (AOP) in Spring Boot
allows developers to separate cross-cutting concerns
like logging, security or transactions from the main
business logic. It complements Object-Oriented
Programming (OOP) by modularizing behaviors that
affect multiple parts of an application, making code
cleaner and more maintainable.
1. Introduction
2. Spring Boot Advices
3. Before
4. After
5. Around
6. After Throwing
7. After Returning
8. AOP vs OOP
9. AOP vs AspectJ
1- Spring Boot - 03
AOP(Aspect Oriented
Programming)
A typical Spring Boot application is structured into
three layers:
Web Layer → Handles client requests (REST
APIs / UI)
Business Layer → Contains core business logic
Data Layer → Manages database and
persistence logic (entities & repositories)
What is AOP?
Aspect Oriented Programming (AOP) is a
programming approach that improves modularity by
separating cross-cutting concerns from business
logic.
It allows adding extra behavior to existing code
without modifying the actual source code.
There are some key terminologies in 04
Aspect-Oriented Programming that
are shown in the tabular manner below as follows:
Terminologies Action Performed
It is a module that provides cross-cutting concerns by encapsulating the
Aspect advice and pointcuts. An application can have any number of aspects in it. In
order to use it, we need to annotate a class with @Aspect annotation.
It is an action that is taken before or after method execution. An action is a
block of code that gets invoked during the execution of a program. The Spring
Advice AOP framework support five type of advice before, after, after-returning,
after-throwing, and around advice. The advice is taken for join points. Advice
is applied over the target object.
Pointcuts are the set of join points where the advice is executed. These
Pointcuts pointcuts are defined using the expression or pattern.
It is a place in an application where the AOP Aspect is applied. A join point can
Join Points be a method execution, exception handling, etc.
Target Object It is an object where the advice is applied. These target objects are proxied
Target objects are proxied which means during the runtime the target
Proxied methods are overridden and depending on method configuration, the advice is
included in the target object.
The process of linking the application with the aspect is called weaving. It can
Weaving be done at load time, compile time and run time.
Why AOP is Needed 05
In real-world applications, certain concerns appear
across all layers, such as:
Logging
Security
Validation
Caching
Transaction management
Implementing these repeatedly in every layer:
Increases code duplication
Makes the code harder to maintain
AOP solves this by centralizing these concerns
in one place.
Core AOP Concepts 06
Aspect : A class that contains cross-cutting logic
(e.g.,logging, security)
Advice: The action performed by the aspect (Before,
After, After Returning, After Throwing, Around)
Pointcut: Defines where the advice should be
applied (method patterns)
Join Point: A specific execution point in the
application (usually a method)
Target Object: The actual object whose method i
being intercepted
Proxy: A wrapper object created at runtime to
apply advice
Weaving: The process of linking aspects with
application code (Compile-time, Load-time, or
Runtime)
Key Benefit of AOP
Keeps business logic clean
Improves maintainability
Reduces code duplication
Makes the application more scalable
and modular
2- Spring Boot - 07
Advices
Spring AOP provides multiple advice annotations to
run code before, after, or around a method execution
without changing business logic.
1. @Before
Runs before the target method executes.
Used for:
Validation
Authorization checks
Pre-processing logic
Example use case:
Check user balance before money transfer in a
banking app.
2. @After 08
Runs after the method finishes, regardless of success
or exception.
Used for:
Logging
Cleanup tasks
Notifications that must always happen
Example use case:
Send order attempt logs even if payment fails.
3. @Around
Runs both before and after the method execution.
It has full control over method execution using
proceed().
Important:
Executes before @Before
Executes after @After
Used for:
Performance monitoring
Execution time tracking
Transaction handling
Best place for common business monitoring logic.
4. @AfterReturning 09
Runs only if the method executes successfully.
Used for:
Logging successful results
Auditing
Sending success notifications
Example use case:
Log returned account status after successful method
execution.
5. @AfterThrowing
Runs only when an exception occurs.
Used for:
Centralized exception handling
Error logging
Alerting systems
Example use case:
Handle IOExceptions, NullPointerExceptions, or
ArithmeticExceptions globally.
10
Execution Order (Important to Remember)
When method succeeds:
1. @Around (Before)
2. @Before
3. Method execution
4. @Around (After)
5. @After
6. @AfterReturning
When method throws exception:
1. @Around (Before)
2. @Before
3. Method execution
4. Exception occurs
5. @After
6. @AfterThrowing
Why Use All Advices Together?
Keeps business logic clean
Centralizes logging & error handling
Improves maintainability
Makes applications production-ready
3- Spring Boot - 11
AOP Before Advice
Concept Recap:
AOP (Aspect-Oriented Programming) allows you
to handle cross-cutting concerns like logging,
security, and validation separately from your
business logic.
Before Advice runs before a target method
executes.
Project Setup
1. Spring Boot Project:
Group: [Link]
Artifact: aop-before-advice-example
Dependencies: spring-boot-starter-web +
spring-boot-starter-aop
2. Student Model 12
3. Student Service
4. Student Controller 13
Aspect – Before Advice
How it works: 14
@Before executes before the
service method (addStudent).
The args(fname, sname) captures method
arguments for logging or validation.
If the advice throws an exception, the service
method won’t execute.
Request:
Key Takeaways:
@Before is ideal for logging, validation,
authentication, or any pre-processing.
Helps keep service methods clean from repetitive
cross-cutting code.
Pointcut expressions and args allow fine-grained
control over which methods and parameters the
advice applies to.
4- Spring Boot - 15
AOP After Advice
Concept Recap:
After Advice runs after a method execution,
regardless of whether it completed normally or
threw an exception.
This differs from:
@AfterReturning → runs only on successful
completion.
@AfterThrowing → runs only when an
exception occurs.
Common use cases: releasing resources,
logging, auditing.
Project Setup
1. Spring Boot Project:
Group: com.after_advice
Artifact: aop-after-advice-example
Dependencies: spring-boot-starter-web +
spring-boot-starter-aop
Steps to Implement AOP After Advice 16
in Spring Boot Application
Step 1: Open Spring Initializer [Link]
Step 2: Provide the Group name: com.after_advice
Step 3: Provide the Artifact Id: aop-after-advice-
example
Step 4: Add the Spring Web dependency.
Step 5: Click on the Generate button. A zip file will be
downloaded into the system. Extract it.
Step 6: Import the folder in the IDE by using
17 the
following steps:
File -> Import -> Existing Maven Projects -> Next ->
Browse -> Look for the folder aop-after-advice-
example -> Finish. When the project is imported, it
will install the dependencies. Once it is done, follow
the next steps.
Step 7: Add the dependency for spring AOP in
[Link]
Step 8: Create a package with the 18
name com.after_advice.model. and
add a Student model class to it.
Student class:
Step 9: Create a package with the name
com.after_advice.service. and add a Student Service
class to it. Add a method to add students with given
name arguments.
StudentService class:
Step 11: Create a package with the 19
name com.after_advice.aspect. and
add a Student Service Aspect class to it.
Here we will add our Advice method and PointCut
expression.
StudentServiceAspect class:
Step 12: Run the Spring Boot app and call:
[Link]
{fname}&secondName={sname} — After Advice
executes after the service method, success or
exception.
5- Spring Boot - 20
AOP Around Advice
Aspect-Oriented Programming (AOP) allows you to
modularize cross-cutting concerns such as logging,
transactions, or security without cluttering business
logic. In AOP, the aspect is the key modular unit, and
advice defines the behavior added to existing code.
Around Advice is the most powerful type of advice
because it runs before and after a method execution.
It can:
Proceed to the join point (method execution) or
bypass it.
Return a custom value or throw an exception.
Be used for caching, logging, timing, or sharing
state in a thread-safe manner.
It is denoted by @Around and requires a
ProceedingJoinPoint parameter. Call proceed() on it
to execute the original method.
21
Steps to Implement AOP Around
Advice in Spring Boot
1- Create Spring Boot Project
Open Spring Initializr
Group: [Link]
Artifact: aop-around-example
Dependency: Spring Web
Generate project and extract the zip.
Import into IDE:
2- Add Spring AOP Dependency in [Link]
22
3- Create Model Class
Package: com.around_advice.model
[Link]
23
4- Create Service Class
Package: com.around_advice.service
[Link]
24
5- Create Controller
Package: com.around_advice.controller
[Link]
6- Create Aspect Class 25
Package: com.around_advice.aspect
[Link]
7- Run the Application 26
Run as Spring Boot Application.
Access the endpoint:
✅ Key Takeaways
@Around gives full control before and after a
method execution.
Use proceed() to call the original method.
Ideal for cross-cutting concerns like logging,
timing, and validation.
Exceptions thrown in the method can prevent the
advice from completing.
6- Spring Boot - 27
AOP After Throwing
Advice
Spring AOP allows handling cross-cutting concerns
like logging, security, or transactions without
cluttering your core business logic. After Throwing
Advice is executed when a proxied method throws an
exception, enabling centralized error handling or
logging.
What is After Throwing Advice?
Executed only if a method throws an exception.
Uses Spring’s JDK dynamic proxies or CGLIB
proxies.
Requires a pointcut expression to define which
method(s) to monitor.
Common use cases: logging exceptions, sending
notifications, or auditing.
Steps to Implement After Throwing 28
Advice in Spring Boot
1️⃣ Generate Spring Boot Project
Go to Spring Initializr
Configure your project (Group, Artifact,
Dependencies: Spring Web)
Generate and extract the ZIP.
Open in IDE.
2️⃣ Add Spring AOP Dependency
In [Link]:
3️⃣ Create Mock DAO
Package: [Link]
[Link]
4 Create Controller 29
Package: [Link]
[Link]
30
5️⃣ Create HTML Page
File: src/main/resources/templates/[Link]
31
6️⃣ Create Aspect Class
Package: [Link]
[Link]
32
7️⃣ Run the Application
1. Run the project:
✅ Key Points
After Throwing Advice executes only on
exceptions.
Centralized exception logging helps maintain
cleaner service and controller code.
Pointcut expressions define exactly which
method(s) to monitor.
7- Spring Boot - 33
AOP After Returning
Advice
Prerequisite: Understanding of Spring Boot and
Aspect-Oriented Programming (AOP).
After Returning Advice is executed only after a join
point (method) completes successfully. If an
exception is thrown, this advice will not be executed.
It is denoted by @AfterReturning.
Steps to Implement AOP After Returning Advice
1️⃣ Generate Spring Boot Project
Go to Spring Initializr
Group: com.after_returning_advice
Artifact: aop-after-returning-advice-example
Dependency: Spring Web
Generate, extract, and import into IDE:
2️⃣ Add Spring AOP Dependency 34
In [Link]:
3️⃣ Create Student Model
Package: com.after_returning_advice.model
[Link]
35
4️⃣ Create Student Service
Package: com.after_returning_advice.service
[Link]
5️⃣ Create Student Controller 36
Package: com.after_returning_advice.controller
[Link]
37
6️⃣ Create Aspect for After Returning Advice
Package: com.after_returning_advice.aspect
[Link]
38
7️⃣ Run the Application
1. Run as Spring Boot Application.
2. Access endpoint:
✅ Key Takeaways
After Returning Advice executes only on
successful method execution.
Useful for logging, auditing, or triggering actions
after a method completes.
Combined with other advices (Before, Around,
After Throwing), you can manage all aspects of
method execution.
8- Spring Boot - 39
AOP After Returning
Advice
Aspect-Oriented Programming (AOP) complements
Object-Oriented Programming (OOP) by modularizing
cross-cutting concerns like logging, security, or
caching, which can affect multiple parts of an
application.
While OOP focuses on modeling real-world entities
using classes and objects, AOP focuses on
separating concerns that cut across multiple classes
to make the program loosely coupled and
maintainable.
1️⃣ Aspect-Oriented Programming 40
Key Points:
Unit of Modularity: Aspect
Purpose: Separates business logic from cross-
cutting concerns.
Annotation: @Aspect,
@EnableAspectJAutoProxy
Frameworks: Spring AOP, AspectJ, JBoss
Advantages:
Focus on business logic
Centralized changes for cross-cutting
concerns
Improves code maintainability and reduces
duplication
Term Description
Aspect A class containing cross-cutting concerns
A point during method execution (e.g., method
Join Point
call)
Action taken at a join point (Before, After
Advice Returning, After Throwing, After Finally,
Around)
Pointcut Expression that matches join points
Example – Before Advice: 41
2️⃣ Object-Oriented Programming (OOP)
Key Points:
Unit of Modularity: Class
Purpose: Models real-world entities using classes
and objects
Components: Classes, Objects, Methods,
Attributes, Interfaces
Advantages:
Code reusability
Modularity
Flexibility
Core Concepts:
Encapsulation – Hide implementation details
Abstraction – Expose only essential features
Inheritance – Reuse properties and behavior
Polymorphism – Objects can take multiple forms
3️⃣ Key Differences: AOP vs OOP 42
Feature AOP OOP
Modularity Unit Aspect Class
Purpose Separate cross-cutting concerns Model entities and business logic
Scope Multiple classes/methods Single class or object
@Aspect, None (uses standard Java
Annotations
@EnableAspectJAutoProxy constructs)
Reuse and centralize common Code reuse, modularity, and
Key Focus
behavior abstraction
Class hierarchies, objects,
Examples of Use Logging, Security, Caching
inheritance
✅ Takeaways:
OOP is the foundation: models entities and their
interactions.
AOP complements OOP by modularizing cross-
cutting concerns.
Together, they improve code maintainability,
flexibility, and reusability in large-scale
applications.
9- Spring Boot - 43
Difference Between
AOP and AspectJ
Spring Boot builds on top of the Spring Framework
and provides a production-ready environment for
rapid development. It simplifies setup and
configuration, making microservice and REST API
development faster and easier. Key Spring Boot
features:
Minimal XML configuration (compared to classic
Spring)
Easy creation and maintenance of REST
endpoints
Embedded Tomcat server
Easy deployment as WAR/JAR files
1️⃣ Understanding Spring AOP 44
Core Terminology:
Term Description
Standalone module containing cross-cutting
Aspect
concerns (e.g., logging)
Point in program execution where an aspect can be
Join Point
applied (e.g., method call)
Code block executed at a join point (before, after,
Advice
or around method execution)
Expression or pattern that selects one or more join
Pointcut
points where advice should run
Example:
@Aspect: Marks the class as 45
containing advice
@Pointcut: Defines the join points where advice
applies
execution(* [Link].*.*(..)): Matches
all methods in [Link] package
2️⃣ AspectJ Overview
AspectJ is a framework for declaring aspects as
regular Java classes with annotations.
Spring interprets AspectJ annotations (AspectJ 5
style) for pointcut parsing and matching.
Important: Spring AOP runtime is still used; there
is no dependency on the AspectJ compiler unless
you specifically use AspectJ weaving.
AspectJ allows inter-type declarations and
compile-time or load-time weaving, while Spring
AOP only supports runtime weaving.
46
3️⃣ Key Differences Between Spring
AOP and AspectJ
Feature Spring AOP AspectJ
Compile-time, Load-time, or
Weaving Type Runtime only
Runtime
Uses runtime proxies (JDK or Can generate woven classes
Proxy
CGLIB) directly
Uses annotations interpreted by Uses annotations or native AspectJ
Aspect Declaration
Spring syntax
Limited (method-level interception Full (supports field access,
Capabilities
only) constructor, static methods, etc.)
Requires AspectJ library for
Dependency Part of Spring framework
parsing/matching
Advanced AOP, cross-cutting
Lightweight AOP for Spring
Use Case concerns across entire Java
applications
applications
47
FOLLOW ME
FOR MORE
Author
Mohamed El Laithy