spring-初始化完成后运行指定内容
生活随笔
收集整理的這篇文章主要介紹了
spring-初始化完成后运行指定内容
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
方案1:繼承ApplicationListener
public class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { //需要執行的邏輯代碼,當spring容器初始化完成后就會執行該方法。 }同時在Spring的配置文件中,添加注入:
<bean class="com.listener.InstantiationTracingBeanPostProcessor"/>但是這個時候,會存在一個問題,在web 項目中(spring mvc),系統會存在兩個容器,一個是root application context ,另一個就是我們自己的 projectName-servlet context(作為root application context的子容器)。
這種情況下,就會造成onApplicationEvent方法被執行兩次。為了避免上面提到的問題,我們可以只在root application context初始化完成后調用邏輯代碼,其他的容器的初始化完成,則不做任何處理,修改后代碼
如下:
public void onApplicationEvent(ContextRefreshedEvent event) { if(event.getApplicationContext().getParent() == null){//root application context 沒有parent,他就是老大. //需要執行的邏輯代碼,當spring容器初始化完成后就會執行該方法。 }?
?
?
?
方法2:使用注解@PostConstruct
只需要在需要啟動的時候執行的方法上標注這個注解就搞定了。
?
@PostConstruct private void startLoad(){Thread t1 = new Thread(new Runnable() {public void run() {refresh();}});t1.start();}?
轉載于:https://www.cnblogs.com/hwaggLee/p/5630816.html
總結
以上是生活随笔為你收集整理的spring-初始化完成后运行指定内容的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到老鼠在床上跑是什么意思
- 下一篇: 做梦梦到门牙掉了一半是什么意思