Spring Boot 启动后运行代码 [英] Running code after Spring Boot starts
问题描述
我想在我的 spring-boot 应用程序开始监视目录更改后运行代码.
I want to run code after my spring-boot app starts to monitor a directory for changes.
我已尝试运行一个新线程,但 @Autowired
服务尚未设置.
I have tried running a new thread but the @Autowired
services have not been set at that point.
我已经能够找到 ApplicationPreparedEvent
,它在设置 @Autowired
注释之前触发.理想情况下,我希望在应用程序准备好处理 http 请求后触发该事件.
I have been able to find ApplicationPreparedEvent
, which fires before the @Autowired
annotations are set. Ideally I would like the event to fire once the application is ready to process http requests.
在应用程序在 spring-boot 中上线后,是否有更好的事件可以使用,或者更好的运行代码的方式?
Is there a better event to use, or a better way of running code after the application is live in spring-boot?
推荐答案
尝试:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {
@SuppressWarnings("resource")
public static void main(final String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
context.getBean(Table.class).fillWithTestdata(); // <-- here
}
}
这篇关于Spring Boot 启动后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!