Spring AOP
Aspect-oriented programming: @Aspect, pointcut expressions, @Before/@After/@Around advice
- Define aspects, join points, and pointcut expressions
- Implement @Around advice for method-level logging and timing
- Apply AOP for cross-cutting concerns: auditing, security, transactions
Series:
Spring Boot Deep Dive | Topic: Spring AOP Level: Intermediate → Advanced | Prerequisite: Spring Beans, Dependency Injection, Java Proxies
Table of Contents
- Complete Code Examples
- Mermaid Diagrams
- Key Observations
- Common Mistakes
- Best Practices
- Interview Notes
- Summary
Overview
Aspect Oriented Programming (AOP) is a programming paradigm that separates cross-cutting concerns from core business logic. In the context of Spring Boot, it provides a mechanism to intercept method invocations and execute additional logic before, after, or around the target method — without modifying the target method itself.
Think of it as placing invisible "hooks" around your methods that spring into action at the right moment.
Why AOP Exists
The Problem Cross-Cutting Concerns
In any enterprise application, business logic is not the only concern. Developers must also handle:
- Logging — printing diagnostic information before/after method calls
- Transaction Management — starting, committing, and rolling back database transactions
- Security — checking whether the caller has permission
- Auditing — recording who called what and when
- Performance Monitoring — timing method execution
Without AOP, these concerns bleed into every class and method:
1// ❌ Without AOP — business logic polluted with boilerplate2public String fetchEmployee() {3 logger.info("Entering fetchEmployee"); // Logging4 transactionManager.begin(); // Transaction5 try {6 String result = employeeRepository.find(); // ← Actual business logic7 transactionManager.commit(); // Transaction8 logger.info("Exiting fetchEmployee"); // Logging9 return result;10 } catch (Exception e) {11 transactionManager.rollback(); // Transaction12 throw e;13 }14}If you have 100 methods, you repeat this boilerplate 100 times. Changing the logging strategy requires modifying all 100 methods.
The AOP Solution
1// ✅ With AOP — business logic is clean2public String fetchEmployee() {3 return employeeRepository.find(); // ← Only business logic4}5
6// Logging, transactions, security handled separately in AspectsAOP says: "You focus on business logic. The boilerplate and repetitive code — I will take care of it."
Benefits
| Benefit | Description |
|---|---|
| Reusability | Write the logging/transaction logic once; apply it everywhere |
| Maintainability | One place to update when logic changes |
| Separation of Concerns | Business logic is clean; cross-cutting logic is isolated |
| Non-invasive | No changes needed to target classes |
Core Terminology
| Term | Definition |
|---|---|
| Aspect | A module (class) that contains cross-cutting logic (logging, transactions, etc.) |
| Pointcut | An expression that identifies which methods the advice should target |
| Advice | The actual code/action to execute (the method inside the Aspect class) |
| JoinPoint | The specific point during program execution where advice is applied (typically a method invocation) |
| Target Object | The bean whose method is being intercepted |
| Proxy | A wrapper object created by Spring around the target object to enable interception |
| Weaving | The process of linking aspects with the application code (Spring does this at runtime) |
Real-World Analogy
Imagine a hotel. The guest just wants to sleep (business logic). But the hotel has:
- Security that checks every guest at entry (Before advice)
- Housekeeping that cleans up after every guest leaves (After advice)
- CCTV that records entry and exit (Around advice)
The guest doesn't know about security or housekeeping — they just use the room. This separation is AOP.
Maven Dependency
To use Spring AOP, add this dependency to your pom.xml:
1<dependency>2 <groupId>org.springframework.boot</groupId>3 <artifactId>spring-boot-starter-aop</artifactId>4</dependency>Core Annotations
| Annotation | Where Used | Purpose |
|---|---|---|
@Aspect | Aspect class | Marks the class as an aspect |
@Component | Aspect class | Registers it as a Spring bean |
@Before | Advice method | Runs before the matched method |
@After | Advice method | Runs after the matched method (finally block equivalent) |
@Around | Advice method | Runs before AND after; you control when the target is called |
@Pointcut | Empty method | Names/reuses a pointcut expression |
@Aspect AND @Component. Without @Component, Spring will not manage it as a bean, and the aspect will never execute.Pointcut
Definition
A Pointcut is an expression that tells Spring AOP: "For which method(s) should this advice be applied?"
It acts as a filter — Spring evaluates the pointcut expression against every managed bean's methods during startup to determine which ones need interception.
Pointcut Types Overview
`execution` Pointcut
◆ Overview
The most powerful and commonly used pointcut type. It matches a specific method in a specific class.
◆ Syntax
1execution([access_modifier] return_type [declaring_type].method_name(parameters) [throws])| Part | Required | Description |
|---|---|---|
access_modifier | ❌ Optional | public, private, protected. If omitted, matches all. |
return_type | ✅ Required | The return type of the method. Use * for any. |
declaring_type | ✅ Required | Full package + class path |
method_name | ✅ Required | Method name. Use * for any. |
parameters | ✅ Required | Parameter types. Use () for none, (..) for any, (*) for exactly one. |
◆ Wildcards
| Wildcard | Meaning |
|---|---|
* | Matches any single item (one return type, one class name, one method name, one parameter) |
.. | Matches zero or more items (zero or more parameters, any sub-packages) |
◆ Examples
Example 1 — Exact method, exact class, no parameters:
1execution(public String com.conceptandcoding.learningspringboot.Employee.fetchEmployee())- Access modifier:
public - Return type:
String - Class:
com.conceptandcoding.learningspringboot.Employee - Method:
fetchEmployee - Parameters: none (empty parentheses)
Example 2 — Any return type, exact class, exact method, no parameters:
1execution(* com.conceptandcoding.learningspringboot.Employee.fetchEmployee())*for return type → matchesString,int,void, any object
Example 3 — Any return type, exact class, any method, one String parameter:
1execution(* com.conceptandcoding.learningspringboot.Employee.*(String))*for method name → matchesfetchEmployee,updateEmployee, etc.(String)→ method must accept exactly oneStringargument
Example 4 — Any return type, exact class, exact method, any parameters (zero or more):
1execution(* com.conceptandcoding.learningspringboot.Employee.fetchEmployee(..))(..)→ matchesfetchEmployee(),fetchEmployee(String),fetchEmployee(String, int), etc.
Example 5 — Any return type, any class in package and sub-packages, exact method name:
1execution(* com.conceptandcoding..fetchEmployee(..))com.conceptandcoding..→ matchescom.conceptandcodingand all its sub-packages- Finds any class in those packages with a method named
fetchEmployee
Example 6 — Any return type, exact class, all methods, any parameters:
1execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*(..))- This matches every method in
EmployeeUtilregardless of name, return type, or parameters
execution is the workhorse of Spring AOP. When in doubt, use execution. It gives you the most control.`within` Pointcut
◆ Overview
Matches all methods within a class or package. No need to specify return type or method name — you just specify the class or package boundary.
◆ Syntax
1within(fully.qualified.ClassName)2within(com.package.*) // All classes in the package3within(com.package..*) // All classes in package and sub-packages◆ Examples
1// All methods in EmployeeController class2within(com.conceptandcoding.learningspringboot.EmployeeController)3
4// All methods in all classes under learningspringboot package and sub-packages5within(com.conceptandcoding.learningspringboot..*)◆ Comparison `execution` vs `within`
| Feature | execution | within |
|---|---|---|
| Granularity | Method-level | Class/package-level |
| Specify return type | Yes | No |
| Specify method name | Yes | No |
| Use case | Precise targeting | Broad class/package targeting |
`@within` Pointcut
◆ Overview
Works like within, but instead of specifying a class path, you specify an annotation. It matches all methods in any class that carries the given annotation.
◆ Syntax
1@within(fully.qualified.AnnotationPath)◆ Example
1@Aspect2@Component3public class LoggingAspect {4
5 @Before("@within(org.springframework.stereotype.Service)")6 public void beforeServiceMethod() {7 System.out.println("Inside before method aspect");8 }9}How it works:
- Spring scans all beans
- If a bean's class has
@Serviceannotation → all its methods are intercepted - If the class does NOT have
@Service→ no interception
◆ Execution Flow Example
1@RestController2public class EmployeeController {3 @Autowired4 private EmployeeUtil employeeUtil;5
6 @GetMapping("/api/fetchEmployee")7 public String fetchEmployee() {8 return employeeUtil.employeeHelperMethod(); // ← This triggers the aspect9 }10}11
12@Service13public class EmployeeUtil {14 public String employeeHelperMethod() { // ← @Service class → intercepted15 System.out.println("Employee helper method call");16 return "item fetch";17 }18}When fetchEmployee API is called:
EmployeeController.fetchEmployee()runs → NOT intercepted (no@Service)EmployeeUtil.employeeHelperMethod()is called → IS intercepted (@Servicepresent)- Advice prints:
Inside before method aspect - Then actual method prints:
Employee helper method call - Returns
"item fetch"
`@annotation` Pointcut
◆ Overview
Matches any method that is directly annotated with a given annotation.
◆ Syntax
1@annotation(fully.qualified.AnnotationPath)◆ Example
1@Aspect2@Component3public class LoggingAspect {4
5 @Before("@annotation(org.springframework.web.bind.annotation.GetMapping)")6 public void beforeGetMappingMethod() {7 System.out.println("Inside before method aspect");8 }9}1@RestController2public class EmployeeController {3
4 @GetMapping("/api/fetchEmployee") // ← Has @GetMapping → intercepted5 public String fetchEmployee() {6 return "item fetch";7 }8}When /api/fetchEmployee is called, Spring sees the @GetMapping annotation on the method → advice fires before the method executes.
@within targets classes with an annotation. @annotation targets methods with an annotation. They are different scopes.`args` Pointcut
◆ Overview
Matches methods based on the type of arguments they accept, regardless of class or method name.
◆ Syntax
1args(TypeA, TypeB, ...)◆ Examples
1// Match any method that takes exactly one String and one int argument2args(String, int)3
4// Match any method that takes an Employee object5args(com.conceptandcoding.learningspringboot.Employee)◆ Full Example
1@Aspect2@Component3public class LoggingAspect {4
5 @Before("args(String, int)")6 public void beforeMethod() {7 System.out.println("Inside before method aspect");8 }9}1@Service2public class EmployeeUtil {3
4 // This method has (String, int) args → INTERCEPTED5 public void employeeHelperMethod(String name, int id) {6 System.out.println("Employee helper method call");7 }8
9 // This method has no args → NOT intercepted10 public String fetchEmployee() {11 return "item fetch";12 }13}`@args` Pointcut
◆ Overview
Similar to args, but matches methods whose argument's class is annotated with a given annotation.
◆ Syntax
1@args(fully.qualified.AnnotationPath)◆ Example
1// Match any method that accepts an argument whose class has @Service annotation2@Before("@args(org.springframework.stereotype.Service)")3public void beforeMethod() {4 System.out.println("Inside before method aspect");5}1@Service // ← EmployeeDao class has @Service2public class EmployeeDao { ... }3
4public class EmployeeUtil {5 // Accepts EmployeeDao which has @Service → INTERCEPTED6 public void processEmployee(EmployeeDao dao) {7 System.out.println("Processing employee");8 }9}@args when you want to intercept based on the nature of what is being passed, not the method signature itself.`target` Pointcut
◆ Overview
Matches any method invoked on a specific class instance (or on an instance of any class implementing a given interface).
◆ Syntax
1target(fully.qualified.ClassName)2target(fully.qualified.InterfaceName) // matches all implementing classes◆ Example Specific Class
1@Aspect2@Component3public class LoggingAspect {4
5 @Before("target(com.conceptandcoding.learningspringboot.EmployeeUtil)")6 public void beforeMethod() {7 System.out.println("Inside before method aspect");8 }9}Whenever any method is called on an instance of EmployeeUtil, the advice fires.
◆ Example Interface (Polymorphism Support)
1public interface Employee {2 String fetchEmployee();3}4
5@Service6public class TempEmployee implements Employee {7 public String fetchEmployee() { return "temp"; }8}9
10@Service11public class PermanentEmployee implements Employee {12 public String fetchEmployee() { return "permanent"; }13}1// Pointcut targets the interface2@Before("target(com.conceptandcoding.learningspringboot.Employee)")3public void beforeMethod() {4 System.out.println("Inside before method aspect");5}Both TempEmployee and PermanentEmployee instances will trigger this advice because they both implement Employee.
target with an interface is very powerful — it handles all current and future implementations automatically.Combining Pointcuts
You can combine multiple pointcut expressions using Boolean operators:
| Operator | Java AOP Syntax | Meaning | ||
|---|---|---|---|---|
| AND | && | Both expressions must match | ||
| OR | `\ | \ | ` | At least one expression must match |
| NOT | ! | Expression must NOT match |
◆ AND Example
1@Before("execution(* com.conceptandcoding.learningspringboot.EmployeeController.*(..)) " +2 "&& @within(org.springframework.web.bind.annotation.RestController)")3public void beforeAndMethod() {4 System.out.println("Inside before AND method aspect");5}This fires only when:
- The method is inside
EmployeeControllerAND - The class has
@RestControllerannotation
Both must be true.
◆ OR Example
1@Before("execution(* com.conceptandcoding.learningspringboot.EmployeeController.*(..)) " +2 "|| @within(org.springframework.stereotype.Component)")3public void beforeOrMethod() {4 System.out.println("Inside before OR method aspect");5}This fires when either condition is true.
◆ Execution Trace for Combined Pointcuts
When fetchEmployee() is called on EmployeeController:
For AND:
execution(...)→ matches ✅@within(@RestController)→EmployeeControllerhas@RestController→ matches ✅- AND result → TRUE → advice fires
For OR:
execution(...)→ matches ✅- OR short-circuits → TRUE → advice fires
Named Pointcuts
◆ Overview
Instead of writing the same pointcut expression multiple times, you can name a pointcut using @Pointcut annotation on an empty method. Other advice methods can then reference this name.
◆ Syntax
1@Pointcut("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*(..))")2public void customPointCutName() {} // Empty method — just a name containerThen reference it:
1@Before("customPointCutName()")2public void beforeMethod() {3 System.out.println("Inside before method aspect");4}◆ Full Example
1@Aspect2@Component3public class LoggingAspect {4
5 // Define the named pointcut6 @Pointcut("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*(..))")7 public void employeeUtilPointcut() {}8
9 // Use it in multiple advice methods10 @Before("employeeUtilPointcut()")11 public void beforeAdvice() {12 System.out.println("Before advice");13 }14
15 @After("employeeUtilPointcut()")16 public void afterAdvice() {17 System.out.println("After advice");18 }19}◆ Benefits of Named Pointcuts
| Benefit | Description |
|---|---|
| DRY | Don't repeat the expression across multiple advice methods |
| Maintainability | Change the expression in one place; all advice methods updated |
| Readability | A descriptive method name communicates intent better than a raw expression |
Advice
Advice is the action that executes when a matched pointcut is triggered. It's the actual method inside your Aspect class that contains the logic (logging, etc.).
Advice Types
`@Before` Advice
Executes before the target method runs. Spring automatically calls the target method after the advice completes — you don't need to do anything manually.
1@Aspect2@Component3public class LoggingAspect {4
5 @Before("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*())")6 public void beforeMethod() {7 System.out.println("Inside before method aspect");8 }9}Execution order:
- Advice method runs → prints
"Inside before method aspect" - Target method runs automatically
`@After` Advice
Executes after the target method completes. Works like a finally block — runs regardless of whether the method threw an exception or not.
1@After("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*())")2public void afterMethod() {3 System.out.println("Inside after method aspect");4}Execution order:
- Target method runs
- Advice method runs → prints
"Inside after method aspect"
@AfterReturning (runs only on successful return) and @AfterThrowing (runs only when an exception is thrown). The lecture focuses on @After which covers both cases.`@Around` Advice
The most powerful advice type. It surrounds the method execution — you control both:
- What happens before the target method
- When the target method actually executes (
proceed()) - What happens after the target method
◆ Key Difference from @Before/@After
With @Before and @After, Spring automatically calls the target method. With @Around, you must explicitly call proceedingJoinPoint.proceed(), or the target method will never execute.
◆ Syntax
1@Around("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*())")2public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {3 // Before logic4 System.out.println("Before the method");5
6 // Call the actual method7 Object result = proceedingJoinPoint.proceed();8
9 // After logic10 System.out.println("After the method");11
12 return result;13}proceedingJoinPoint.proceed() inside @Around advice unless you intentionally want to skip the method execution (e.g., for caching). Forgetting to call proceed() will silently skip your business logic.◆ Use Cases for @Around
| Use Case | Example |
|---|---|
| Performance monitoring | Time the method execution |
| Caching | Return cached result without calling method |
| Retry logic | Retry the method on failure |
| Transaction management | Begin before, commit/rollback after |
| Security | Check permission before, log result after |
JoinPoint
A JoinPoint represents the specific point in program execution where advice is applied — in Spring AOP, this is always a method invocation.
JoinPoint vs ProceedingJoinPoint
| Type | Used With | Purpose |
|---|---|---|
JoinPoint | @Before, @After | Read-only access to method info (name, args, target) |
ProceedingJoinPoint | @Around | All of JoinPoint + ability to call proceed() |
Accessing JoinPoint Information
1@Before("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*(..))")2public void beforeMethod(JoinPoint joinPoint) {3 System.out.println("Method: " + joinPoint.getSignature().getName());4 System.out.println("Args: " + Arrays.toString(joinPoint.getArgs()));5 System.out.println("Target: " + joinPoint.getTarget().getClass().getName());6}How AOP Works Internally
This is where AOP becomes truly elegant. Understanding the internals removes the "magic" and reveals a well-designed system.
Application Startup Flow
◆ Step 1 Scan for @Aspect Classes
Spring Boot scans the classpath and finds all classes annotated with @Aspect. It knows these classes contain pointcut expressions and advice methods.
◆ Step 2 Parse Pointcut Expressions
Spring uses AspectJ's PointcutParser to parse and compile the pointcut expressions (like execution( com.example.EmployeeUtil.(..))) into an efficient internal representation (AST/data structure). This is done once at startup, not on every method call — that's why there is no runtime overhead per method invocation for matching.
◆ Step 3 Store in Cache
The parsed expressions are cached so that during actual method invocations, matching is fast (no re-parsing).
◆ Step 4 Scan All Beans
Spring then scans all other beans (@Component, @Service, @RestController, etc.). For each bean, it checks: "Does any parsed pointcut expression match any method in this class?"
◆ Step 5 Create Proxy if Eligible
If a bean requires interception, Spring does not register the original bean. Instead, it creates a proxy object that wraps the original. The proxy is what gets injected everywhere.
JDK Dynamic Proxy vs CGLib Proxy
| Feature | JDK Dynamic Proxy | CGLib Proxy |
|---|---|---|
| Mechanism | Implements the same interface | Creates a subclass |
| Requirement | Class must implement an interface | Works for any class |
| Speed | Slightly slower (reflection) | Slightly faster (bytecode generation) |
final methods | Not applicable | Cannot proxy final methods |
spring.aop.proxy-target-class=false.◆ What the Proxy Looks Like (Conceptual)
Original class:
1public class EmployeeUtil {2 public String fetchEmployee() {3 return "Fetching employee details";4 }5}CGLib-generated proxy (conceptual — not actual code):
1public class EmployeeUtil$$EnhancerByCGLIB$$abc123 extends EmployeeUtil {2 @Override3 public String fetchEmployee() {4 // Generated intercept code5 return SpringAopInterceptor.intercept(this, "fetchEmployee", args, ...);6 }7}The proxy class overrides every intercepted method and routes the call through Spring's advice chain.
Advice Chain Chain of Responsibility
When a method call is intercepted, Spring builds an ordered chain of advice and processes them using a recursive proceed mechanism.
◆ Internal Code Flow (Simplified)
Step 1: Caller calls a method on the proxy object.
Step 2: Proxy routes to CglibAopProxy.intercept() (or JdkDynamicAopProxy.invoke())
Step 3: Spring creates a ReflectiveMethodInvocation with the list of matched interceptors (advice chain).
Step 4: proceed() is called. It iterates through the chain using a counter:
- Each interceptor gets control, runs its "before" part, then calls
proceed()again - When the counter reaches the end of the chain, the actual target method is invoked
- As the recursion unwinds, "after" parts of each interceptor run
Step 5: The result propagates back up the chain.
◆ Why This is Elegant
The chain-of-responsibility pattern means:
- Adding/removing advice doesn't change the target class
- The order of advice can be controlled with
@Order - Multiple aspects can apply to the same method transparently
chain.doFilter() to pass control forward, then does cleanup when it returns — identical to how AOP advice works.Complete Code Examples
Example 1 Basic @Before Advice
1// Target class2@Service3public class EmployeeUtil {4 public String fetchEmployee() {5 System.out.println("Fetching employee details");6 return "item fetch";7 }8}9
10// Controller11@RestController12public class EmployeeController {13 @Autowired14 private EmployeeUtil employeeUtil;15
16 @GetMapping("/api/fetchEmployee")17 public String fetchEmployee() {18 return employeeUtil.fetchEmployee();19 }20}21
22// Aspect23@Aspect24@Component25public class LoggingAspect {26
27 @Before("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.fetchEmployee())")28 public void beforeMethod() {29 System.out.println("Inside before method aspect");30 }31}Inside before method aspect Fetching employee details
Example 2 @Before and @After Together
1@Aspect2@Component3public class LoggingAspect {4
5 @Before("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*())")6 public void beforeMethod() {7 System.out.println("Inside before method aspect");8 }9
10 @After("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*())")11 public void afterMethod() {12 System.out.println("Inside after method aspect");13 }14}Inside before method aspect Fetching employee details Inside after method aspect
Example 3 @Around Advice with Timing
1@Aspect2@Component3public class PerformanceAspect {4
5 @Around("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*(..))")6 public Object measureTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {7 long start = System.currentTimeMillis();8 System.out.println("Before method: " + proceedingJoinPoint.getSignature().getName());9
10 Object result = proceedingJoinPoint.proceed(); // Call actual method11
12 long end = System.currentTimeMillis();13 System.out.println("After method. Time taken: " + (end - start) + "ms");14
15 return result;16 }17}Before method: fetchEmployee Fetching employee details After method. Time taken: 3ms
Example 4 Named Pointcut + Multiple Advice
1@Aspect2@Component3public class LoggingAspect {4
5 // Named pointcut6 @Pointcut("execution(* com.conceptandcoding.learningspringboot.EmployeeUtil.*(..))")7 public void employeeUtilMethods() {}8
9 @Before("employeeUtilMethods()")10 public void beforeAdvice(JoinPoint joinPoint) {11 System.out.println("Before: " + joinPoint.getSignature().getName());12 }13
14 @After("employeeUtilMethods()")15 public void afterAdvice(JoinPoint joinPoint) {16 System.out.println("After: " + joinPoint.getSignature().getName());17 }18}Example 5 @annotation Pointcut (targets @GetMapping methods)
1@Aspect2@Component3public class ApiLoggingAspect {4
5 @Before("@annotation(org.springframework.web.bind.annotation.GetMapping)")6 public void logGetRequest(JoinPoint joinPoint) {7 System.out.println("GET request to: " + joinPoint.getSignature().getName());8 }9}Example 6 target with Interface (Polymorphism)
1public interface Employee {2 String fetchEmployee();3}4
5@Service6@Qualifier("tempEmployee")7public class TempEmployee implements Employee {8 public String fetchEmployee() {9 return "Temp Employee";10 }11}12
13@Service14@Qualifier("permanentEmployee")15public class PermanentEmployee implements Employee {16 public String fetchEmployee() {17 return "Permanent Employee";18 }19}20
21// Aspect22@Aspect23@Component24public class LoggingAspect {25
26 @Before("target(com.conceptandcoding.learningspringboot.Employee)")27 public void beforeMethod() {28 System.out.println("Inside before method aspect");29 }30}Both TempEmployee.fetchEmployee() and PermanentEmployee.fetchEmployee() trigger the advice.
Mermaid Diagrams
AOP Architecture Overview
Pointcut Expression Anatomy
| Color | Part | Required |
|---|---|---|
| 🟠 Orange | Access Modifier | Optional |
| 🔵 Blue | Return Type | Required |
| 🟣 Purple | Package + Class | Required |
| 🟢 Green | Method Name | Required |
| 🔴 Red | Parameters | Required |
Advice Chain Internals
JDK vs CGLib Proxy Decision
Key Observations
- @Aspect alone is not enough — you must also add
@Component(or other stereotype annotation) so Spring manages the class as a bean.
- Pointcut expressions are parsed once at startup, not re-evaluated on every method call. This makes AOP performant even with many aspects.
- The proxy is what gets injected, not the original bean. When you
@AutowireanEmployeeUtil, you receiveEmployeeUtil$$EnhancerByCGLib$$..., not the original.
- Self-invocation does NOT trigger AOP. If
methodA()callsthis.methodB()in the same class,methodB()will NOT be intercepted because the call goes throughthis(the original object), not through the proxy.
@Aroundrequires explicitproceed()call. Forgetting it silently skips the target method.
finalmethods cannot be proxied by CGLib — they cannot be overridden. Avoidfinalon methods that need AOP.
privatemethods cannot be proxied — Spring AOP works at the proxy level, which only intercepts public/protected calls from outside.
Common Mistakes
Mistake 1 Forgetting @Component on Aspect Class
1// ❌ Wrong — Spring won't manage this; aspect never fires2@Aspect3public class LoggingAspect {4 @Before("execution(* com.example.EmployeeUtil.*())")5 public void before() { ... }6}7
8// ✅ Correct9@Aspect10@Component11public class LoggingAspect {12 @Before("execution(* com.example.EmployeeUtil.*())")13 public void before() { ... }14}Mistake 2 Self-Invocation Bypass
1@Service2public class OrderService {3 public void placeOrder() {4 // This will NOT trigger AOP on processPayment!5 this.processPayment(); // ← 'this' is the raw object, not the proxy6 }7
8 public void processPayment() { ... } // Has @Around aspect9}Fix: Inject the service into itself (self-injection) or use ApplicationContext to get the proxy:
1@Service2public class OrderService {3 @Autowired4 private OrderService self; // Injects the proxy5
6 public void placeOrder() {7 self.processPayment(); // Now goes through proxy → AOP fires8 }9}Mistake 3 Forgetting `proceed()` in @Around
1// ❌ Wrong — target method never executes!2@Around("execution(* com.example.EmployeeUtil.*())")3public Object around(ProceedingJoinPoint pjp) throws Throwable {4 System.out.println("Before");5 // Missing pjp.proceed() → target method skipped!6 System.out.println("After");7 return null;8}9
10// ✅ Correct11@Around("execution(* com.example.EmployeeUtil.*())")12public Object around(ProceedingJoinPoint pjp) throws Throwable {13 System.out.println("Before");14 Object result = pjp.proceed(); // Target method runs here15 System.out.println("After");16 return result;17}Mistake 4 Placing Aspect on final Methods
1@Service2public class EmployeeUtil {3 // ❌ CGLib cannot override final methods — aspect will NOT fire4 public final String fetchEmployee() {5 return "item fetch";6 }7}Remove final from methods that need to be intercepted.
Best Practices
- Name your pointcuts — use
@Pointcutto give reusable names instead of repeating raw expressions.
- Keep aspects focused — one aspect per concern (one for logging, one for transactions, one for security).
- Use
executionas default — it gives the most control. Switch towithinor@annotationonly when you genuinely need class/annotation-level matching.
- Use
@Aroundfor transaction management — it's the only advice type that can rollback (control the call flow) and wrap the entire operation cleanly.
- Order your aspects — use
@Order(n)on Aspect classes to control which advice fires first when multiple aspects apply to the same method.
- Avoid logic in pointcut expressions — keep pointcuts simple. Complex logic belongs in the advice method.
- Log with JoinPoint — always accept
JoinPointin your advice methods to log meaningful context (method name, arguments, target class).
Interview Notes
Commonly Asked Questions
Q: What is the difference between @Before, @After, and @Around? A: @Before runs before the method; Spring automatically calls the method. @After runs after the method (like finally). @Around surrounds the method — you must call proceed() to execute it and can run logic before and after.
Q: What is the difference between JDK Dynamic Proxy and CGLib proxy? A: JDK Dynamic Proxy requires the target class to implement an interface; it creates a proxy that also implements the interface. CGLib works for any class by creating a subclass. Spring Boot 2.x defaults to CGLib.
Q: Why doesn't AOP work on private methods? A: Spring AOP uses proxies. A proxy can only intercept calls that go through it (external calls). Private methods are only accessible within the class (this), so they bypass the proxy entirely.
Q: What is the difference between @within and @annotation? A: @within matches all methods in classes annotated with the given annotation. @annotation matches methods that are directly annotated with the given annotation.
Q: What is self-invocation problem in AOP? A: When a method in a class calls another method in the same class using this, the call bypasses the proxy and AOP does not intercept it. Solution: use self-injection to call through the proxy.
Q: How are pointcut expressions evaluated — at startup or at runtime? A: Pointcut expressions are parsed and cached at application startup. At runtime, the proxy simply calls the pre-computed advice chain, so there is no repeated matching overhead.
Q: What is weaving? A: Weaving is the process of applying aspects to target objects. Spring performs runtime weaving — aspects are applied when the application starts by creating proxies. AspectJ also supports compile-time and load-time weaving.
Q: Can you apply multiple aspects to the same method? A: Yes. Spring builds an ordered advice chain. Use @Order on Aspect classes to control the sequence.
Related Concepts
@Transactional— implemented internally using AOP (@Aroundadvice that manages transactions)@Cacheable— implemented using AOP (checks cache before calling method)- Spring Security — method-level security (
@PreAuthorize) uses AOP - AspectJ — the full AspectJ framework supports compile-time and load-time weaving (Spring AOP uses only runtime proxy-based weaving)
- Decorator Pattern — AOP proxy is conceptually a decorator
- Chain of Responsibility — the advice chain follows this pattern
Practice Questions
Easy
- What annotation do you need on an Aspect class in addition to
@Aspect? - Write a pointcut expression that matches all methods in
com.example.UserService. - What wildcard matches zero or more items in a pointcut expression?
- What is a JoinPoint?
Medium
- Write a
@Aroundadvice that logs the time taken by every method in theServiceLayerpackage. - What is the difference between
target(EmployeeUtil)andwithin(EmployeeUtil)? - Why does self-invocation bypass AOP, and how do you fix it?
- Write a named pointcut that matches all
@GetMappingmethods, then use it in a@Beforeadvice.
Hard
- Explain in detail how Spring builds and processes the advice chain when a proxied method is called.
- If a class implements
Employeeinterface, what type of proxy does Spring create by default in Spring Boot 2.x? Why? - Write an
@Aroundaspect that retries a method up to 3 times if it throws a specific exception. - How would you order two aspects that both apply to the same method? What happens if you don't specify order?
Summary
| Concept | Key Point |
|---|---|
| AOP Purpose | Separate cross-cutting concerns (logging, transactions) from business logic |
| Aspect | Class annotated with @Aspect + @Component that contains advice |
| Pointcut | Expression defining which methods to intercept |
| Advice | Method in the Aspect that contains the actual logic to run |
| JoinPoint | The intercepted method invocation point |
| Proxy | Wrapper object created by Spring; the actual bean injected into dependents |
| @Before | Runs before target method; Spring handles calling the target |
| @After | Runs after target method (like finally) |
| @Around | Surrounds the method; must call proceed() to invoke the target |
| execution | Pointcut for specific method in specific class; most flexible |
| within | Pointcut for all methods in a class/package |
| @within | Like within but matches by annotation on the class |
| @annotation | Matches methods annotated with a given annotation |
| args | Matches methods by argument types |
| target | Matches methods called on a specific class or interface |
| JDK Proxy | Used when class implements interface; implements same interface |
| CGLib Proxy | Used when class has no interface; extends the class |
| Self-invocation | this.method() bypasses the proxy — AOP does not fire |
| Named Pointcut | @Pointcut on empty method to reuse expression across advice |
| Advice Chain | Spring builds a recursive chain; each interceptor calls proceed() |
@Transactional is one of the most common uses of AOP in Spring. Understanding AOP internals fully explains why @Transactional doesn't work on private methods or self-invoked methods — the same proxy limitations apply.End of Spring AOP Study Guide
Mastery check
How well can you recall this?
Finished this lesson?