2015-02-09 32 views
2

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

+2

如果问题是该方法需要1小时才能执行,请在不同的线程中异步运行它。 – 2015-02-09 17:49:29

+0

这不是问题。问题是如何告诉Spring在服务器启动时执行此代码。 – user2455862 2015-02-09 17:58:40

+0

你可以在@PostConstruct注释的方法中运行它吗?您可以通过从注释方法调用runnable来异步运行它。 – minion 2015-02-09 18:21:35

回答

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。正如评论中所建议的那样,您可以在另一个线程上执行代码。

3

为了更清晰起见,您可以这样做@PostConstruct。把下面的代码放在你配置spring中定义的singleton 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()); 
    } 
}