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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23325666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:56:32  来源:igfitidea点击:

Run a method only at Spring Application Context startup?

javaspringtomcatspring-mvc

提问by user3120173

I need to run a method after the Spring Application Context of my web app has started up. I looked at this questionbut it refers to Java Servlet startup, and none of the Spring stuff has run at that point.

我需要在 Web 应用程序的 Spring 应用程序上下文启动后运行一个方法。我查看了这个问题,但它指的是 Java Servlet 启动,并且此时没有任何 Spring 内容运行。

Is there a "SpringContext.onStartup()" method I can hook into?

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

采纳答案by geoand

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 上下文),则此方法将为每个上下文运行一次。

回答by Krishna

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" />

回答by Reva

Have a look at Better application events in Spring Framework 4.2

查看Spring Framework 4.2 中的 Better application events

@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 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 注释托管 bean 的方法以自动注册与方法签名匹配的 ApplicationListener。@EventListener 是一个核心注释,以与 @Autowired 和其他类似的方式透明处理:java 配置不需要额外的配置,现有的 < context:annotation-driven/> 元素可以完全支持它。