In a spring boot app (2.3), is it possible to have a method be executed after context is initialized, but before the app starts to take requests? I don't know if becoming ready to accept requests is part of the spring context initialization or if that is a separate step.
Note that ideally if this method throws an exception, the service fails to start, but that is not a requirement.
I tried ContextRefreshedEvent
. However, the app is accepting requests at that point. (While my ContextRefreshedEvent
event listener method is executing, requests can come in and execute at the same time.)
(I can't use @PostContruct
, because my method depends on many different beans being initialized.)
The specific use case is that I have a spring cloud config server. I want it to pre-load authentication data into cache prior to accepting requests. The loading of this data depends on bootstrap/app config files being loaded, ApplicationEnvironmentPreparedEvent
listener being called, beans being constructed, etc.
As Andy Wilkinson pointed out (thank you!), to do this, implement a bean's method with the desired behavior and add the @PostConstruct annotation. The method will be called after all beans are initialized (and environment prepared) but before the service starts taking requests.