[英]Run a method only at Spring Application Context startup?
I need to run a method after the Spring Application Context of my web app has started up. 我需要在我的Web应用程序的Spring Application Context启动后运行一个方法。 I looked at this question but it refers to Java Servlet startup, and none of the Spring stuff has run at that point.
我看了这个问题,但是它指的是Java Servlet启动,并且当时没有Spring的东西运行。
Is there a "SpringContext.onStartup()" method I can hook into? 有没有我可以挂钩的“SpringContext.onStartup()”方法?
Use something like the following code: 使用类似下面的代码:
@Component
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
// do your stuff here
}
}
Of course StartupListener will need to be within the component scan's reach 当然,StartupListener需要在组件扫描的范围内
Take note however that if your application uses multiple contexts (for example a root context and a web context) this method will be run once for each context. 但请注意,如果您的应用程序使用多个上下文(例如根上下文和Web上下文),则此方法将针对每个上下文运行一次。
You can write listener like this: 你可以写这样的监听器:
@Component
public class SpringContextListener implements ApplicationListener<ApplicationEvent> {
public void onApplicationEvent(ApplicationEvent arg0) {
System.out.println("ApplicationListener");
};
}
Just add component scan path like this: 只需像这样添加组件扫描路径:
<context:component-scan base-package="com.controller" />
Have a look at Better application events in Spring Framework 4.2 在Spring Framework 4.2中查看更好的应用程序事件
@Component
public class MyListener {
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
...
}
}
Annotate a method of a managed-bean with @EventListener to automatically register an ApplicationListener matching the signature of the method. 使用@EventListener注释托管bean的方法,以自动注册与方法签名匹配的ApplicationListener。 @EventListener is a core annotation that is handled transparently in a similar fashion as @Autowired and others: no extra configuration is necessary with java config and the existing < context:annotation-driven/> element enables full support for it.
@EventListener是一个核心注释,它以与@Autowired和其他类似的方式透明地处理:java配置不需要额外的配置,现有的<context:annotation-driven />元素可以完全支持它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.