1. 程式人生 > >spring 容器初始化完成後執行某個方法

spring 容器初始化完成後執行某個方法

一下內容來自internet,後面會整理

在做web專案開發中,尤其是企業級應用開發的時候,往往會在工程啟動的時候做許多的前置檢查。

比如檢查是否使用了我們組禁止使用的MySQL的group_concat函式,如果使用了專案就不能啟動,

在Spring容器將所有的Bean都初始化完成之後,就會執行該方法它有onApplicationEvent()方法

並指出哪個檔案的xml檔案使用了這個函式。而在spring的web專案中,我們可以介入Spring的啟動過程。

我們希望在Spring容器將所有的Bean都初始化完成之後,做一些操作,這個時候我們就可以實現一個介面:

@Service
public class
StartAddDataListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if(event.getApplicationContext().getParent() == null)//root application context 沒有parent,他就是老大. { //需要執行的邏輯程式碼,當spring容器初始化完成後就會執行該方法。
  1. logger.info("★★★★★★★★★★★★★★★★★★★★★★★★★★★");  
  2.                 logger.info("============quartz 初始化完成===========");  
  3.                 logger.info("★★★★★★★★★★★★★★★★★★★★★★★★★★★");  
  4.                 Scheduler scheduler = new StdSchedulerFactory().getScheduler();  
  5.                 scheduler.start();  
} //或者下面這種方式 if(event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) {
  1. logger.info("★★★★★★★★★★★★★★★★★★★★★★★★★★★");  
  2.                 logger.info("============quartz 初始化完成===========");  
  3.                 logger.info("★★★★★★★★★★★★★★★★★★★★★★★★★★★");  
  4.                 Scheduler scheduler = new StdSchedulerFactory().getScheduler();  
  5.                 scheduler.start();  
} } }

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(DemoApplication .class);
springApplication.addListeners(new

StartAddDataListener
());
springApplication.run(args);
}

}

   被@PreDestroy修飾的方法會在伺服器解除安裝Servlet的時候執行,並且只會被伺服器呼叫一次,類似於Servlet的destroy()方法。被@PreDestroy修飾的方法會在destroy()方法之後執行,在Servlet被徹底解除安裝之前。(詳見下面的程式實踐)