我想在我的 spring-boot 应用程序开始监视目录的更改后运行代码。
我尝试运行一个新线程,但此时尚未设置服务。@Autowired
我已经能够找到 ,在设置注释之前触发。理想情况下,我希望在应用程序准备好处理 http 请求后触发事件。ApplicationPreparedEvent
@Autowired
是否有更好的事件可以使用,或者在应用程序在 spring-boot 中上线后运行代码的更好方法?
就这么简单:
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
System.out.println("hello world, I have just started up");
}
在版本上测试1.5.1.RELEASE
尝试:
@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
}
}
你试过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;
}
}
代码来自: http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/
这是文档提到的有关启动事件的内容:
…
应用程序事件在应用程序运行时按以下顺序发送:
ApplicationStartedEvent 在运行开始时发送,但在除侦听器和初始值设定项的注册之外的任何处理之前
发送。当上下文中使用的环境已知时,但在创建上下文
之前,将发送应用程序环境准备事件。应用程序准备事件在刷新开始之前发送,但在装入 Bean 定义之后发送。
刷新后将发送 ApplicationReadyEvent,并且已处理任何相关的回调,以指示应用程序已准备好为
请求提供服务。如果启动时出现异常,则发送应用程序失败事件。
…
模板简介:该模板名称为【Java 中 spring-boot 启动后运行代码】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。