简体   繁体   English

Spring 4-服务器启动后运行方法

[英]Spring 4 - run method after server starts

I need to run some code just after server starts. 服务器启动后,我需要运行一些代码。 I used ServletContextListener and it worked good, however... it run the code before server started. 我使用了ServletContextListener,它运行良好,但是...它在服务器启动之前运行代码。 Because of that I got the timeout exception on server as it cannot start because my method is still running. 因此,我在服务器上收到了超时异常,因为它无法启动,因为我的方法仍在运行。 There is no point in increasing the timeout time as this method takes about 1 hour. 没有必要增加超时时间,因为此方法大约需要1个小时。 What should I do? 我该怎么办?

For better clarity, this is how you can do @PostConstruct. 为了更好的说明,这是您可以执行@PostConstruct的方法。 Put the below code in any of you config singleton bean defined in spring. 将以下代码放入spring中定义的任何配置单例bean中。 For more details read what and how Postconstruct works. 有关更多详细信息,请阅读Postconstruct的内容和工作方式。 This should help you to load async after server is started. 这应该有助于您在服务器启动后加载异步。

    public class singletonBeanConfig{
SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new SimpleAsyncTaskExecutor();

private class SampleConfigurator implements Runnable {

        @Override
        public void run() {
            // run you process here.            
        }

    }

@PostConstruct
    public final void initData() {
        // this will be executed when the config singleton is initialized completely.
        this.simpleAsyncTaskExecutor.execute(new SampleConfigurator());
    }
}

You can use an ApplicationListener 您可以使用ApplicationListener

    public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

      public void onApplicationEvent(final ContextRefreshedEvent event) {
        ApplicationContext ctx = event.getApplicationContext();
        (new Thread() {
           public void run() {
             // do stuff
           }
         }).start();
      }

    }

Just register that as a Spring bean. 只需将其注册为Spring bean。 As suggested in the comments, you can execute the code on another thread. 如注释中所建议,您可以在另一个线程上执行代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM