Affects: 5.3.10


I'm using AspectJ @EnableCaching(mode = AdviceMode.ASPECTJ).

Invoking an @Cacheable method from a bean's @PostConstruct method doesn't work, because the cache aspect is not initialized. (see code).

The Cache aspect is a SmartInitializingSingleton and is initialized too late, after my bean was already created.

My use case: populate cache at startup, before accepting web requests.

Comment From: sbrannen

Hi @cdalexndr,

Did this work for you in a previous version of the Spring Framework?

If so, which version?

Comment From: cdalexndr

@sbrannen no, this is my first attempt.

Comment From: sbrannen

My use case: populate cache at startup, before accepting web requests.

Have you tried implementing an ApplicationListener that reacts to the ContextRefreshedEvent application event to populate the cache?

Comment From: cdalexndr

The ContextRefreshedEvent is sent too late, after tomcat server has started. Tomcat starts at WebServerStartStopLifecycle.start(). which is called in getLifecycleProcessor().onRefresh() just before the event is published. Note that I'm using Spring Boot 2.4.11

Comment From: sbrannen

Since you're using Spring Boot, have you tried listening to Boot's ApplicationStartedEvent?

Comment From: cdalexndr

Same issue with ApplicationStartedEvent, it's published after tomcat has started.

Comment From: sbrannen

The ContextRefreshedEvent is sent too late, after tomcat server has started. Tomcat starts at WebServerStartStopLifecycle.start(). which is called in getLifecycleProcessor().onRefresh() just before the event is published. Note that I'm using Spring Boot 2.4.11

Since there is no ApplicationEvent that suits your needs, you'll need to implement and register a custom org.springframework.context.SmartLifecycle bean that populates your cache in a phase before the phase of the WebServerStartStopLifecycle.

Please give that a try and let us know if that solves your issue.

Comment From: cdalexndr

This works, but it's only a workaround. When using @Cacheable annotations, the aspect bean should be initialized so that the operation behaves as expected.

Comment From: snicoll

The reference documentation states that that you should not rely on this feature in your initialization code.