简体   繁体   中英

Execute method after Spring context initialized but before requests are accepted

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM