我想在spring-boot应用程序开始监视目录更改之后运行代码。
我已经尝试运行一个新线程,但@Autowired服务还没有设置在那一点。
我已经能够找到ApplicationPreparedEvent,它在@Autowired注释设置之前触发。理想情况下,我希望事件在应用程序准备好处理http请求时触发。
是否有更好的事件可以使用,或者在应用程序在spring-boot中激活后运行代码的更好方法?
我想在spring-boot应用程序开始监视目录更改之后运行代码。
我已经尝试运行一个新线程,但@Autowired服务还没有设置在那一点。
我已经能够找到ApplicationPreparedEvent,它在@Autowired注释设置之前触发。理想情况下,我希望事件在应用程序准备好处理http请求时触发。
是否有更好的事件可以使用,或者在应用程序在spring-boot中激活后运行代码的更好方法?
当前回答
为spring boot应用程序实现CommandLineRunner。 你需要实现run方法,
public classs SpringBootApplication implements CommandLineRunner{
@Override
public void run(String... arg0) throws Exception {
// write your logic here
}
}
其他回答
“Spring Boot”方式是使用CommandLineRunner。只需添加该类型的bean,就可以了。在Spring 4.1 (Boot 1.2)中,也有一个SmartInitializingBean,它在所有东西初始化后得到一个回调。还有SmartLifecycle(来自Spring 3)。
使用CommandLineRunner或ApplicationRunner的最佳方式 两者之间唯一的区别是run()方法 CommandLineRunner接受字符串数组,ApplicationRunner接受应用参数。
为什么不创建一个bean,在初始化时启动监视器呢?
@Component
public class Monitor {
@Autowired private SomeService service
@PostConstruct
public void init(){
// start your monitoring in here
}
}
在为bean完成任何自动装配之前,不会调用init方法。
其实很简单:
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
System.out.println("hello world, I have just started up");
}
在1.5.1.RELEASE版本上测试
为spring boot应用程序实现CommandLineRunner。 你需要实现run方法,
public classs SpringBootApplication implements CommandLineRunner{
@Override
public void run(String... arg0) throws Exception {
// write your logic here
}
}