Category: java
Introduction to Spring AOP
Published on 24 Jul 2026
Explanation
Spring AOP (Aspect-Oriented Programming) separates cross-cutting concerns such as logging, auditing, security, and performance monitoring from business logic. This keeps the application modular, reusable, and easier to maintain.
Code:
@Aspect
@Component
public class LoggingAspect {
}
Explanation
The @Before advice executes before a target method is called. It is commonly used to log method names, input parameters, and request details before business logic begins execution.
Code:
@Before("execution(* com.example.service.*.*(..))")
public void logRequest(JoinPoint joinPoint) {
System.out.println("Calling: " + joinPoint.getSignature().getName());
}
Explanation
The @AfterReturning advice executes after a method completes successfully. It is useful for auditing successful operations, tracking user activities, and recording changes made to business data.
Code:
@AfterReturning("execution(* com.example.service.*.*(..))")
public void auditSuccess() {
System.out.println("Operation completed successfully");
}
Explanation
The @Around advice surrounds the execution of a method, allowing code to run before and after it. It is commonly used to measure execution time, monitor performance, and detect slow-running methods.
Code:
@Around("execution(* com.example.service.*.*(..))")
public Object monitor(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
System.out.println("Execution Time: " + (System.currentTimeMillis() - start) + " ms");
return result;
}
Explanation
To use Aspect-Oriented Programming, enable AOP support in the Spring Boot application using @EnableAspectJAutoProxy. Spring automatically detects aspect classes and applies advice to matching methods during runtime.
Code:
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}