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

时间:2015-02-09 17:43:39

标签: java spring

我需要在服务器启动后运行一些代码。我使用了ServletContextListener并且它运行良好,但是......它在服务器启动之前运行代码。因为我在服务器上得到了超时异常,因为它无法启动,因为我的方法仍在运行。增加超时时间没有意义,因为此方法需要大约1小时。我该怎么办?

2 个答案:

答案 0 :(得分:3)

为了更清晰,这就是你如何做@PostConstruct。将以下代码放在spring中定义的任何配置单例bean中。有关详细信息,请阅读Postconstruct的工作原理和方式。这应该可以帮助您在服务器启动后加载异步。

    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());
    }
}

答案 1 :(得分:2)

您可以使用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();
      }

    }

只需将其注册为Spring bean即可。正如评论中所建议的那样,您可以在另一个线程上执行代码。