本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看<活动链接>
提问:Spring Boot启动后运行代码 我想在我的spring-boot应用程序开始监视目录更改后运行代码。
我尝试运行新线程,但此时@Autowired尚未设置服务。
我已经能够找到ApplicationPreparedEvent,它会在设置@Autowired注释之前触发。理想情况下,一旦应用程序准备好处理HTTP请求,我希望就触发该事件。
回答1:
你可以试试:
@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
}
}
回答2: 您是否尝试过ApplicationReadyEvent?
@Component
public class ApplicationStartup
implements ApplicationListener<ApplicationReadyEvent> {
/**
* This event is executed as late as conceivably possible to indicate that
* the application is ready to service requests.
*/
@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
// here your code ...
return;
}
}
应用程序事件在您的应用程序运行时按以下顺序发送:
1,ApplicationStartedEvent在运行开始时发送,但在除侦听器和初始化程序的注册之外的任何处理之前发送。
2,当已知要在上下文中使用的环境时,但在创建上下文之前,将发送ApplicationEnvironmentPreparedEvent。
3,在刷新开始之前,但在加载Bean定义之后,发送了ApplicationPreparedEvent。
4,刷新后,将发送ApplicationReadyEvent,并且已处理所有相关的回调,以指示应用程序已准备好处理请求。
5,如果启动时发生异常,则发送ApplicationFailedEvent。
该文章翻译至Stack OverFlow:stackoverflow.com/questions/2…