仅在Spring Application Context启动时运行方法?

时间:2014-04-27 16:07:16

标签: java spring tomcat spring-mvc

我需要在我的Web应用程序的Spring Application Context启动后运行一个方法。我查看了this question,但它引用了Java Servlet启动,并且当时没有Spring的东西运行。

是否有" SpringContext.onStartup()"方法我可以挂钩?

3 个答案:

答案 0 :(得分:14)

使用类似下面的代码:

@Component
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {

  @Override
  public void onApplicationEvent(final ContextRefreshedEvent event) {
    // do your stuff here 
  }
}

当然,StartupListener需要在组件扫描范围内

请注意,如果您的应用程序使用多个上下文(例如根上下文和Web上下文),则此方法将针对每个上下文运行一次。

答案 1 :(得分:4)

你可以写这样的听众:

@Component
public class SpringContextListener implements ApplicationListener<ApplicationEvent> {
    public void onApplicationEvent(ApplicationEvent arg0) {
        System.out.println("ApplicationListener");
    };
}

只需像这样添加组件扫描路径:

<context:component-scan base-package="com.controller" />

答案 2 :(得分:4)

查看Better application events in Spring Framework 4.2

@Component
public class MyListener {

    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent event) {
       ...
    }
}

使用@EventListener注释托管bean的方法,以自动注册与方法签名匹配的ApplicationListener。 @EventListener是一个核心注释,以与@Autowired和其他类似的方式透明地处理:java配置和现有的&lt;不需要额外的配置。上下文:注解驱动/&GT; element可以完全支持它。