[英]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?在 Spring Boot 应用程序 (2.3) 中,是否可以在上下文初始化之后但在应用程序开始接受请求之前执行方法? I don't know if becoming ready to accept requests is part of the spring context initialization or if that is a separate step.
我不知道准备好接受请求是否是 spring 上下文初始化的一部分,或者这是一个单独的步骤。
Note that ideally if this method throws an exception, the service fails to start, but that is not a requirement.请注意,理想情况下,如果此方法引发异常,服务将无法启动,但这不是必需的。
I tried ContextRefreshedEvent
.我试过
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.) (当我的
ContextRefreshedEvent
事件侦听器方法正在执行时,请求可以进入并同时执行。)
(I can't use @PostContruct
, because my method depends on many different beans being initialized.) (我不能使用
@PostContruct
,因为我的方法取决于正在初始化的许多不同的 bean。)
The specific use case is that I have a spring cloud config server.具体用例是我有一个 spring 云配置服务器。 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.此数据的加载取决于正在加载的引导程序/应用程序配置文件、正在调用的
ApplicationEnvironmentPreparedEvent
侦听器、正在构造的 bean 等。
As Andy Wilkinson pointed out (thank you!), to do this, implement a bean's method with the desired behavior and add the @PostConstruct annotation.正如 Andy Wilkinson 指出的(谢谢!),要做到这一点,请实现具有所需行为的 bean 方法并添加 @PostConstruct 注释。 The method will be called after all beans are initialized (and environment prepared) but before the service starts taking requests.
该方法将在所有bean 初始化(并准备好环境)之后但在服务开始接受请求之前调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.