2015-02-09 34 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()); 
    } 
}