Spring AOP Overview
Spring AOP Overview Interview with follow-up questions
1. What is Spring AOP and what are its advantages?
Spring AOP is Spring's proxy-based AOP framework for modularizing cross-cutting concerns. You write aspects using the @AspectJ annotation style (@Aspect + advice + pointcuts), and Spring applies them by wrapping beans in runtime proxies. It's deliberately simpler than full AspectJ — limited to method-execution join points on Spring-managed beans — which covers the vast majority of real needs.
Advantages:
- Declarative & low-boilerplate — annotate an aspect; no manual interception code.
- Modularity & reuse — one aspect applies across many beans via a pointcut.
- Loose coupling — business code is unaware of the woven concern.
- Integrated — it's the engine behind
@Transactional,@Cacheable,@Async, and method security, so you often use Spring AOP without writing an aspect at all.
@Aspect @Component
class Metrics {
@Around("@within(org.springframework.stereotype.Service)")
Object measure(ProceedingJoinPoint pjp) throws Throwable { return pjp.proceed(); }
}
The framing that signals current knowledge: enable it with spring-boot-starter-aop; remember the self-invocation caveat and that only Spring beans' methods are advised. When you need richer join points (constructors, field access) or compile/load-time weaving, step up to AspectJ.
Follow-up 1
Can you explain the term 'cross-cutting concerns' in the context of AOP?
Cross-cutting concerns are the functionalities or requirements that are common and can be applied to multiple components or modules in an application. These concerns typically cut across the core business logic and are not specific to a particular module or component. Examples of cross-cutting concerns include logging, security, transaction management, caching, and error handling. In the context of AOP, cross-cutting concerns are modularized and separated from the core business logic, allowing them to be applied to multiple components or modules without duplicating code.
Follow-up 2
How does Spring AOP handle exceptions?
Spring AOP provides a way to handle exceptions using the @AfterThrowing advice type. This advice type allows developers to specify a method that should be executed when an exception is thrown from a join point. The method annotated with @AfterThrowing can have an additional parameter of the exception type, which will receive the thrown exception. This allows developers to perform specific exception handling logic, such as logging the exception or performing recovery actions. Here's an example:
@Aspect
public class ExceptionHandlingAspect {
@AfterThrowing(pointcut = "execution(* com.example.MyService.*(..))", throwing = "ex")
public void handleException(Exception ex) {
// Perform exception handling logic
// e.g., log the exception or perform recovery actions
}
}
Follow-up 3
What are the different types of advice in Spring AOP?
Spring AOP provides several types of advice that can be used to intercept method invocations at different join points. The different types of advice in Spring AOP are:
Before advice: Executed before a join point, allowing developers to perform actions before the method invocation.
After returning advice: Executed after a join point successfully completes, allowing developers to perform actions after the method invocation and obtain the return value.
After throwing advice: Executed after a join point throws an exception, allowing developers to perform exception handling logic.
After advice: Executed after a join point, regardless of whether it completes successfully or throws an exception.
Around advice: Wraps around a join point, allowing developers to control the method invocation by providing custom pre- and post-processing logic.
Introduction advice: Introduces new interfaces and methods to a target object.
Follow-up 4
How does Spring AOP differ from AspectJ?
Spring AOP and AspectJ are both AOP frameworks, but they differ in several ways:
Proxy-based vs. bytecode weaving: Spring AOP uses dynamic proxies or CGLIB proxies to intercept method invocations at runtime, while AspectJ uses bytecode weaving to modify the compiled bytecode of the target classes.
Configuration style: Spring AOP can be configured using annotations or XML configuration, making it easier to integrate with existing Spring applications. AspectJ, on the other hand, requires the use of AspectJ-specific syntax and configuration files.
Dependency: Spring AOP is part of the Spring Framework and can be used independently or alongside other Spring features. AspectJ, on the other hand, is a standalone framework that can be used with or without Spring.
Flexibility: AspectJ provides more advanced features and fine-grained control over the weaving process, making it suitable for complex AOP scenarios. Spring AOP, on the other hand, provides a simpler and more lightweight approach to AOP.
2. How does Spring AOP work internally?
Internally, Spring AOP is proxy-based and wires up at bean creation:
- At startup, a
BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator) scans for@Aspectbeans and their pointcuts. - For each bean whose methods match a pointcut, it creates a proxy — a JDK dynamic proxy (if the bean implements an interface) or a CGLIB subclass (Spring Boot's default).
- The container injects the proxy instead of the raw target.
- At call time, the proxy runs an interceptor chain of matching advice (
@Aroundcan wrap and must callproceed();@Before/@AfterReturning/@AfterThrowing/@Afterrun at their points), then delegates to the target method.
inject → Proxy → [advice chain] → target.method() → [advice chain] → return
The gotchas that prove understanding: advice applies only to calls routed through the proxy — external calls to a Spring bean's methods — so self-invocation bypasses it, which is why an internal @Transactional call silently does nothing. Spring AOP advises method executions only (no field/constructor join points), and proxies can't override final methods/classes. This same proxy/interceptor machinery is what implements @Transactional, @Cacheable, and @Async.
Follow-up 1
What is a pointcut in Spring AOP?
A pointcut in Spring AOP is an expression that defines the join points where advice should be applied. It specifies the methods or locations in the code where the advice should be executed. Pointcuts can be defined using various expressions, such as method names, method signatures, annotations, or regular expressions.
Follow-up 2
What is a join point in Spring AOP?
A join point in Spring AOP is a specific point in the execution of a program, such as the execution of a method or the handling of an exception. Join points are identified by pointcuts and are the points where advice can be applied. For example, a join point can be the execution of a specific method in a class.
Follow-up 3
How is an advice applied to a pointcut?
An advice is applied to a pointcut in Spring AOP by associating the advice with the pointcut. This is done using the AOP configuration, where the advice and pointcut are defined and linked together. When the join point specified by the pointcut is reached during program execution, the advice associated with the pointcut is executed.
Follow-up 4
Can you explain the concept of weaving in Spring AOP?
Weaving in Spring AOP is the process of applying the advice to the target object to create the proxy object. There are two types of weaving: compile-time weaving and runtime weaving. Compile-time weaving modifies the source code of the target object during compilation, while runtime weaving modifies the bytecode of the target object at runtime. Spring AOP primarily uses runtime weaving to create the proxy object and apply the advice.
3. What is the role of a proxy in Spring AOP?
The proxy is the mechanism that makes Spring AOP work: a wrapper object around the target bean that intercepts method calls and runs the configured advice before/after/around the real method, adding cross-cutting behavior without modifying the target's code.
Concretely, the proxy's role is to:
- Stand in for the target — Spring injects the proxy, not the raw bean.
- Run the advice chain at each advised method call, then delegate to the target.
- Decouple concerns (transactions, security, logging) from business logic.
Spring builds it as a JDK dynamic proxy (interface-based) or CGLIB subclass (no interface; Boot default).
client → proxy.save() → [tx begin / log] → target.save() → [tx commit / log]
The implications interviewers want stated: because the behavior lives in the proxy, it only triggers on calls that pass through the proxy — so self-invocation (this.method()) and final/private methods escape advice. This is the standard explanation for "why isn't my @Transactional/@Cacheable working when called from within the same class?" — the call never went through the proxy.
Follow-up 1
How does Spring AOP create proxies?
Spring AOP can create proxies using either JDK dynamic proxies or CGLIB proxies.
JDK dynamic proxies are created by implementing the target object's interfaces. The proxy object delegates method invocations to an InvocationHandler, which can intercept and modify the method behavior.
CGLIB proxies are created by subclassing the target object's class. The proxy object overrides the target object's methods to intercept and modify the method behavior.
Spring AOP automatically chooses the appropriate proxy mechanism based on the target object's characteristics. If the target object implements at least one interface, JDK dynamic proxies are used. Otherwise, CGLIB proxies are used.
Follow-up 2
What is the difference between JDK dynamic proxies and CGLIB proxies in Spring AOP?
The main difference between JDK dynamic proxies and CGLIB proxies in Spring AOP is the way they create proxies.
JDK dynamic proxies create proxies by implementing the target object's interfaces. This means that the target object must implement at least one interface for JDK dynamic proxies to work. The proxy object delegates method invocations to an InvocationHandler.
CGLIB proxies create proxies by subclassing the target object's class. This means that the target object does not need to implement any interfaces. The proxy object overrides the target object's methods to intercept and modify the method behavior.
Another difference is that JDK dynamic proxies can only intercept public methods, while CGLIB proxies can intercept both public and protected methods.
Follow-up 3
When would you use one type of proxy over the other?
You would use JDK dynamic proxies when the target object implements at least one interface and you only need to intercept public methods. JDK dynamic proxies have a smaller memory footprint and better performance compared to CGLIB proxies.
You would use CGLIB proxies when the target object does not implement any interfaces or when you need to intercept both public and protected methods. CGLIB proxies have a larger memory footprint and slightly slower performance compared to JDK dynamic proxies.
4. How can you define an aspect in Spring AOP?
Define an aspect as a Spring bean annotated @Aspect (plus @Component so it's picked up), containing pointcut definitions and advice methods:
@Aspect
@Component
public class LoggingAspect {
@Pointcut("execution(* com.app.service..*(..))") // where
void serviceMethods() {}
@Before("serviceMethods()") // advice + when
public void logEntry(JoinPoint jp) {
log.info("Entering {}", jp.getSignature());
}
@Around("@annotation(com.app.Timed)") // pointcut by annotation
public Object time(ProceedingJoinPoint pjp) throws Throwable {
long t = System.nanoTime();
try { return pjp.proceed(); }
finally { log.info("took {}ns", System.nanoTime() - t); }
}
}
The pieces: advice annotations (@Before, @After, @AfterReturning, @AfterThrowing, @Around) each take a pointcut expression — either inline or a reference to a @Pointcut method — using execution(...), @annotation(...), within(...), @within(...), etc.
Setup notes interviewers like: add spring-boot-starter-aop (Boot auto-enables AspectJ auto-proxying; otherwise add @EnableAspectJAutoProxy). @Around must call proceed() and can modify args/return value. Remember aspects only advise Spring beans' method executions, and watch the self-invocation caveat.
Follow-up 1
What are the different ways to define pointcuts?
There are several ways to define pointcuts in Spring AOP:
Using the @Pointcut annotation: The @Pointcut annotation can be used to define a reusable pointcut expression. This expression can then be referenced in advice methods.
Using the execution() pointcut designator: The execution() pointcut designator allows you to define pointcuts based on the execution of specific methods.
Using the within() pointcut designator: The within() pointcut designator allows you to define pointcuts based on the execution of methods within specific types or packages.
Using the bean() pointcut designator: The bean() pointcut designator allows you to define pointcuts based on the names of Spring beans.
These are some of the commonly used ways to define pointcuts in Spring AOP.
Follow-up 2
Can you explain the @Aspect annotation?
The @Aspect annotation is used to mark a class as an aspect in Spring AOP. An aspect is a modularization of a concern that cuts across multiple classes. The @Aspect annotation is typically used in combination with other annotations such as @Pointcut, @Before, @After, etc., to define the advice methods and pointcuts for the aspect.
Here's an example of how the @Aspect annotation can be used:
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class LoggingAspect {
// Advice methods and pointcuts go here
}
Follow-up 3
How can you define advice in Spring AOP?
In Spring AOP, advice can be defined as methods within an aspect class. These methods are annotated with annotations such as @Before, @After, @Around, etc., to specify the type of advice and the join points at which the advice should be applied.
Here's an example of how advice can be defined in Spring AOP:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void beforeAdvice() {
// Advice logic goes here
}
}
Follow-up 4
What is the order of execution of advice in Spring AOP?
In Spring AOP, the order of execution of advice depends on the type of advice:
Before advice: Before advice is executed before the join point method is invoked.
After returning advice: After returning advice is executed after the join point method has successfully completed.
After throwing advice: After throwing advice is executed if the join point method throws an exception.
After advice: After advice is executed regardless of the outcome (success or exception) of the join point method.
Around advice: Around advice wraps around the join point method and can control the entire execution flow.
The order of execution of advice can be controlled using the @Order annotation or by implementing the Ordered interface.
5. Can you explain the concept of introduction in Spring AOP?
Introduction (a.k.a. inter-type declaration) is a special AOP feature that lets an aspect add new interfaces and their implementations to an existing bean — effectively making the proxied bean implement an additional interface it didn't originally, without changing its source. It's about adding new behavior/state to a type, as opposed to ordinary advice, which wraps existing method calls.
In Spring AOP you declare it with @DeclareParents:
@Aspect @Component
class AuditableMixin {
@DeclareParents(value = "com.app.service.*+",
defaultImpl = AuditableImpl.class)
private Auditable auditable; // every matched bean now also "is" Auditable
}
// elsewhere: ((Auditable) someService).markAudited();
Points worth making: introductions apply at the class/type level (a pointcut over types), not at method-execution join points like normal advice. They're a niche feature — useful for mixing a common capability into many beans — but used far less than @Before/@Around advice in practice, so it's fine to know the concept and the @DeclareParents mechanism without over-emphasizing it. (Full AspectJ offers richer inter-type declarations than Spring's proxy-based subset.)
Follow-up 1
How is introduction different from other types of advice?
Introduction is different from other types of advice in Spring AOP in the sense that it allows you to add new methods or attributes to a class, whereas other types of advice (such as before, after, or around advice) only allow you to intercept and modify the behavior of existing methods. Introduction is a way to enhance the functionality of a class without modifying its source code.
Follow-up 2
Can you give an example of when you would use an introduction?
Sure! Let's say you have a class called 'User' that represents a user in your application. You want to add a 'getFullName' method to the 'User' class, which concatenates the first name and last name of the user. Instead of modifying the 'User' class directly, you can use introduction to add the 'getFullName' method to the 'User' class. This way, you can keep the 'User' class clean and separate the concern of getting the full name into a separate class.
Follow-up 3
How can you implement an introduction in Spring AOP?
To implement an introduction in Spring AOP, you need to follow these steps:
Create an interface that defines the new methods or attributes you want to introduce.
Create a class that implements the interface and provides the implementation for the introduced methods or attributes.
Configure the introduction in the Spring AOP configuration file by using the 'introduction' element and specifying the target class and the interface to be introduced.
Use the introduced methods or attributes in your application as if they were part of the target class. Spring AOP will dynamically add the introduced functionality to the target class at runtime.
Live mock interview
Mock interview: Spring AOP Overview
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.