Chapter 13

AOP, events, async, scheduling and caching

Five features that all rest on the same mechanism: the proxy. Learn it once here and the limitations of all five stop being surprising.

⏱ 22 min readLevel: intermediate → advanced

How proxies work

When a bean needs interception, Spring does not give other beans your object. It gives them a wrapper that implements the same type, does something extra, then delegates.

JDK dynamic proxyCGLIB proxy
RequiresThe bean implements an interfaceA non-final class
MechanismImplements the interfaceGenerates a subclass
Boot default—Always CGLIB since Boot 2.0
Cannot interceptNon-interface methodsprivate, final, static
The four proxy rules — memorise these

1. Self-invocation (this.method()) bypasses the proxy entirely.
2. private, final and static methods are never intercepted.
3. A call from a constructor or @PostConstruct happens before the proxy exists.
4. No warning is ever logged. The annotation simply does nothing.

This one paragraph explains "my @Transactional didn't roll back", "my @Async ran on the caller thread", "my @Cacheable queries every time" and "my @PreAuthorize let everyone through".

Aspect-oriented programming

pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
common/aop/TimingAspect.java
@Aspect
@Component
public class TimingAspect {

    private static final Logger log = LoggerFactory.getLogger(TimingAspect.class);

    /* a named pointcut — reusable and self-documenting */
    @Pointcut("within(com.bitsnippets.bookstore..*Service)")
    void anyService() { }

    @Pointcut("@annotation(com.bitsnippets.bookstore.common.aop.Timed)")
    void annotatedTimed() { }

    @Around("anyService() || annotatedTimed()")
    public Object time(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.nanoTime();
        String method = joinPoint.getSignature().toShortString();
        try {
            return joinPoint.proceed();
        } finally {
            long millis = (System.nanoTime() - start) / 1_000_000;
            if (millis > 200) {
                log.warn("Slow call {} took {} ms", method, millis);
            }
        }
    }

    @AfterThrowing(pointcut = "anyService()", throwing = "ex")
    public void logFailure(JoinPoint joinPoint, Throwable ex) {
        log.error("{} threw {}", joinPoint.getSignature().toShortString(),
                  ex.getClass().getSimpleName());
    }
}
AdviceRunsCan
@Beforebefore the methodthrow to prevent it
@Afteralways, aftercleanup
@AfterReturningafter successinspect the result
@AfterThrowingafter an exceptioninspect it (not swallow it)
@Aroundwraps the calleverything — modify args, result, or skip the call
pointcut expressions worth knowing
execution(* com.bitsnippets..*Service.*(..))     any method on any *Service
within(com.bitsnippets.bookstore.catalog..*)     any bean in this package tree
@annotation(com.example.Audited)                 methods annotated @Audited
@within(org.springframework.stereotype.Service)  every method of any @Service
bean(*Repository)                                by bean name pattern
args(java.lang.Long, ..)                         first argument is a Long
Use AOP sparingly

Behaviour that appears from nowhere is hard to debug and invisible in a stack trace. Good uses: timing, auditing, retry, correlation ids. Bad uses: business rules, validation, anything a reader of the method needs to know about. Before writing an aspect, check whether Micrometer's @Observed or Spring Retry already does it.

Application events

Events decouple "something happened" from "and therefore do these five things". They are also the cleanest way out of a circular dependency.

publishing
public record BookPublishedEvent(Long bookId, String title, Instant occurredAt) { }

@Service
public class BookService {

    private final ApplicationEventPublisher events;

    @Transactional
    public Book publish(Long id) {
        Book book = require(id);
        book.setStatus(BookStatus.PUBLISHED);

        events.publishEvent(new BookPublishedEvent(book.getId(),
                                                   book.getTitle(),
                                                   Instant.now()));
        return book;
    }
}
listening
@Component
public class BookPublishedListeners {

    /* synchronous, same transaction — keep it fast */
    @EventListener
    public void updateSearchIndex(BookPublishedEvent event) {
        searchIndex.add(event.bookId(), event.title());
    }

    /* only after the transaction commits — for external side effects */
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void notifySubscribers(BookPublishedEvent event) {
        notifier.announce(event.title());
    }

    /* after commit AND on another thread */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void warmCaches(BookPublishedEvent event) {
        cacheWarmer.warm(event.bookId());
    }

    /* conditional, using SpEL against the event */
    @EventListener(condition = "#event.title.startsWith('Effective')")
    public void featureIt(BookPublishedEvent event) { }
}
Built-in eventFired when
ApplicationStartedEventContext refreshed, runners not yet executed
ApplicationReadyEventFully started — the right hook for warm-up
ApplicationFailedEventStartup failed
ContextClosedEventShutdown begins
AvailabilityChangeEventLiveness or readiness changed
Events are in-process, not a message queue

They are synchronous by default, run in the same JVM, and are lost on a crash. They are excellent for decoupling modules inside one application. They are not a substitute for Kafka or RabbitMQ when the delivery must survive a restart.

@Async

common/AsyncConfig.java
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(16);
        executor.setQueueCapacity(200);
        executor.setThreadNamePrefix("async-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(30);
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        // void @Async methods swallow exceptions without this
        return (ex, method, params) ->
                log.error("Async failure in {}", method.getName(), ex);
    }
}
using it
@Service
public class ReportService {

    @Async
    public void generateInBackground(Long id) {           // fire and forget
        // exceptions go to the AsyncUncaughtExceptionHandler
    }

    @Async("taskExecutor")
    public CompletableFuture<Report> generate(Long id) {   // awaitable
        return CompletableFuture.completedFuture(build(id));
    }
}

// combining several
CompletableFuture<Report> a = reportService.generate(1L);
CompletableFuture<Report> b = reportService.generate(2L);
CompletableFuture.allOf(a, b).join();
Three ways @Async silently does nothing useful

Self-invocation — runs synchronously on the caller thread.
No executor defined — Boot falls back to a SimpleAsyncTaskExecutor that creates an unbounded number of threads. Under load that is an OOM.
Thread-locals do not travel — the security context, the MDC trace id and the transaction are all bound to the calling thread. The async thread has none of them unless you propagate them explicitly.

// propagate the security context to async threads
@Bean
static MethodInvokingFactoryBean securityContextStrategy() {
    MethodInvokingFactoryBean bean = new MethodInvokingFactoryBean();
    bean.setTargetClass(SecurityContextHolder.class);
    bean.setTargetMethod("setStrategyName");
    bean.setArguments(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
    return bean;
}
Virtual threads (Java 21)

For I/O-bound work, virtual threads often remove the need to tune pools at all. One property switches Tomcat and the task executors over:

spring:
  threads:
    virtual:
      enabled: true

Caveat: synchronized blocks around blocking I/O pin the carrier thread and undo the benefit. Prefer ReentrantLock in hot paths.

@Scheduled

common/CleanupJobs.java
@Configuration
@EnableScheduling
public class SchedulingConfig {

    @Bean
    TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(4);                // default is 1 — jobs would queue up
        scheduler.setThreadNamePrefix("sched-");
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        return scheduler;
    }
}

@Component
public class CleanupJobs {

    /* fixed delay: waits N ms AFTER the previous run finished */
    @Scheduled(fixedDelayString = "${bookstore.cleanup.delay:PT5M}")
    public void purgeExpiredReservations() { }

    /* fixed rate: starts every N ms regardless of duration — can overlap */
    @Scheduled(fixedRate = 60_000, initialDelay = 30_000)
    public void refreshExchangeRates() { }

    /* cron: sec min hour day month weekday */
    @Scheduled(cron = "0 0 3 * * *", zone = "Europe/Berlin")
    public void nightlyReindex() { }

    @Scheduled(cron = "${bookstore.report.cron}")
    public void weeklyReport() { }
}
Scheduled jobs and multiple instances

Run three replicas and your "nightly" job runs three times, concurrently. Options, in order of preference: use a real scheduler (Quartz with a JDBC store, or your platform's cron), use ShedLock for distributed locking, or take an advisory lock in the database as the first statement of the job. A profile that enables jobs on only one instance is fragile — that instance will eventually be the one that is down.

@Cacheable

common/CacheConfig.java
@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    CacheManager cacheManager(Caffeine<Object, Object> caffeine) {
        CaffeineCacheManager manager = new CaffeineCacheManager("books", "categories");
        manager.setCaffeine(caffeine);
        return manager;
    }

    @Bean
    Caffeine<Object, Object> caffeine() {
        return Caffeine.newBuilder()
                .maximumSize(10_000)
                .expireAfterWrite(Duration.ofMinutes(10))
                .recordStats();                   // feeds Actuator metrics
    }
}
catalog/CategoryService.java
@Service
public class CategoryService {

    @Cacheable(value = "categories", key = "#id")
    public Category find(Long id) {
        return repository.findById(id).orElseThrow();
    }

    /* do not cache empty results */
    @Cacheable(value = "books", key = "#isbn", unless = "#result == null")
    public Book findByIsbn(String isbn) { }

    /* always run, and refresh the cached value */
    @CachePut(value = "categories", key = "#category.id")
    public Category update(Category category) {
        return repository.save(category);
    }

    @CacheEvict(value = "categories", key = "#id")
    public void delete(Long id) { }

    @CacheEvict(value = "categories", allEntries = true)
    @Scheduled(cron = "0 0 4 * * *")
    public void evictAllNightly() { }
}
Caching pitfalls

Self-invocation — same proxy rule; the cache is skipped.
Bad keys — the default key is all method arguments. If one is an object without a good hashCode, you get a permanent miss or a wrong hit. Be explicit with key = "#id".
Local caches in a cluster — Caffeine is per-JVM, so instance B keeps serving what instance A just changed. Use Redis when you scale out.
Caching mutable objects — callers can mutate the cached instance. Cache immutable records.

application.yml — Redis for multi-instance
spring:
  cache:
    type: redis
    redis:
      time-to-live: 10m
      cache-null-values: false
      key-prefix: "bookstore:"
  data:
    redis:
      host: redis
      port: 6379

Bonus: retries

Spring Retry
@EnableRetry
@Configuration
public class RetryConfig { }

@Service
public class InventoryClient {

    @Retryable(retryFor = { ResourceAccessException.class, HttpServerErrorException.class },
               maxAttempts = 3,
               backoff = @Backoff(delay = 200, multiplier = 2, random = true))
    public StockLevel stockFor(String isbn) { }

    @Recover
    public StockLevel fallback(Exception ex, String isbn) {
        log.warn("Inventory unavailable for {}, assuming zero", isbn);
        return StockLevel.unknown(isbn);
    }
}

Retry only idempotent operations, always with jittered exponential backoff, and never retry a 4xx — the request will not become valid on the second attempt.

Checklist

  • No self-invocation of any annotated method.
  • Annotated methods are public, non-final, non-static.
  • @Async has an explicit bounded executor and an exception handler.
  • Side effects that must not happen on rollback use AFTER_COMMIT.
  • Scheduled jobs are guarded against running on every replica.
  • Cache keys are explicit; cached values are immutable.
  • Aspects are limited to cross-cutting concerns, never business rules.

You add @Async to a method and it still blocks the caller. The method is public and @EnableAsync is present. Why?

Self-invocation is the answer to a remarkable share of Spring questions. this.x() is a plain Java call — the proxy that would have submitted the work to an executor is never involved. Move the method to another bean.