Field note / Aspect-Oriented Programming
Demystifying Aspect-Oriented Programming (AOP) in Java: A Practical Introduction
An introduction to AOP in Java with two practical Spring examples: automatic cache invalidation and pausing scheduled jobs in maintenance mode.
If you’ve been coding in Java for a while, you’ve likely faced a situation where you needed to perform cross-cutting tasks—like logging, caching, or security checks—across multiple parts of your application. Wouldn’t it be nice to handle these tasks elegantly, without cluttering your core business logic? Enter Aspect-Oriented Programming (AOP).
In this post, we’ll dive into the basics of AOP in Java and show you how to use it with two practical examples: automatically invalidating a cache after saving a user, and pausing scheduled jobs during maintenance. Let’s go!
What Is Aspect-Oriented Programming?
AOP is a programming paradigm that helps you separate cross-cutting concerns (tasks that affect multiple modules, like logging or caching) from your business logic. Instead of sprinkling these tasks throughout your codebase, you can define them in one place and “weave” them into the parts of your application where they’re needed.
Think of it like adding a spell to your application: “Whenever a method matching this pattern is called, apply this magical behavior.”
Key AOP Terminology
- Aspect: A module that encapsulates a cross-cutting concern (e.g., caching or logging).
- Advice: The action to perform. Types include:
@Before: Runs before a method execution.@After: Runs after a method execution, whether it returned or threw.@AfterReturning: Runs only after a method returns successfully.@Around: Wraps a method, running custom logic before and after.
- Join Point: A specific point in your application, like a method call.
- Pointcut: An expression that matches join points.
A Practical Example: Caching with AOP
Let’s say you’re building a user management system with a UserRepository and a cache (fullUserCache). When a user is saved, you need to invalidate their cache entry—without modifying the repository code.
Step 1: Add Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Step 2: Write the Aspect
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class UserCacheAspect {
private final FullUserCache fullUserCache;
public UserCacheAspect(FullUserCache fullUserCache) {
this.fullUserCache = fullUserCache;
}
@AfterReturning("execution(* com.test.repository.UserRepository.save(..)) && args(user)")
public void onSaveUserRemove(User user) {
fullUserCache.invalidate(user.getId());
System.out.println("Cache invalidated for user ID: " + user.getId());
}
}
Step 3: Break Down the Code
@Aspect: Marks this class as an aspect.- Pointcut Expression:
execution(* com.test.repository.UserRepository.save(..)) && args(user)targets thesavemethod and captures theUserargument. @AfterReturning: Runs only aftersavereturns successfully. Plain@Afteralso runs whensavethrows, which would evict the cache for a write that never happened.
If your cache is a Spring CacheManager cache, @CacheEvict on the method does the same job without an aspect. The aspect earns its place when the cache is something else, like the FullUserCache here, or when you’d rather not touch the repository.
Step 4: Test the Magic
User user = new User(1, "Alice");
userRepository.save(user);
// Output: Cache invalidated for user ID: 1
A Second Example: Pausing Scheduled Jobs in Maintenance Mode
@After-style advice reacts to a method. @Around advice can decide whether the method runs at all. A common use: your app has dozens of @Scheduled jobs, and during maintenance you want them all to stand down. Adding the same if to every job is repetitive and easy to forget on the next one.
Step 1: Create a Marker Annotation
package com.test.helpers;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ConditionalScheduled {
}
Step 2: Implement the Aspect
package com.test.helpers;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Aspect
@Component
@Slf4j
public class ScheduledAspect {
private final Environment environment;
public ScheduledAspect(Environment environment) {
this.environment = environment;
}
@Around("@annotation(com.test.helpers.ConditionalScheduled)")
public Object aroundScheduledMethod(ProceedingJoinPoint joinPoint) throws Throwable {
if (environment.getProperty("maintenance.mode.enabled", Boolean.class, false)) {
log.info("Maintenance mode is ON. Skipping scheduled task: {}", joinPoint.getSignature().toShortString());
return null;
}
return joinPoint.proceed();
}
}
joinPoint.proceed()runs the actual job. Returning without calling it skips the job.- The flag is read on every run, not once at startup. A value captured in the constructor would need a restart to change, which defeats the point of a maintenance switch.
Step 3: Annotate Your Jobs
@Component
public class SampleJob {
@Scheduled(cron = "0 0 * * * ?")
@ConditionalScheduled
public void runHourlyTask() {
System.out.println("Executing hourly task...");
}
}
# application.properties
maintenance.mode.enabled=true
A value in application.properties is still fixed for the life of the process. To flip it without a deploy, back the property with something that changes at runtime: a refreshable config source, a feature-flag service, or a row in your database that the aspect reads instead.
Why Use AOP?
- Cleaner Code: Keep your business logic focused on its core responsibility.
- Reusability: Write cross-cutting logic once, apply it everywhere.
- Maintainability: Centralize logic for easier updates.
When Not to Use AOP
- It can make your application harder to debug (hidden logic).
- Complex pointcut expressions might confuse future developers.
- You lose explicitness; not everyone likes “magic.”
- Spring AOP works through proxies, so a call from one method to another in the same class skips the aspect entirely. That’s the most common reason “my aspect doesn’t fire.”
Conclusion
Aspect-Oriented Programming in Java, especially with Spring AOP, is a powerful tool for managing cross-cutting concerns like caching, logging, and security. In this post, we used one aspect to invalidate a cache after a successful save and another to pause scheduled jobs during maintenance, without touching the repository or the jobs themselves.