一、如果我們希望在Spring容器將所有的Bean都初始化完成之后,做一些操作,那么就可以使用ApplicationListener接口,實現ApplicationListener接口中的onApplicationEvent方法,此方法會在容器中所有bean初始化完成后執行。
@Component public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Autowired private ApplicationContext applicationContext; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { System.out.println("容器初始化完成。。。。。。。。"); } }
二、在web開發中,會存在一個問題,系統會存在兩個容器,一個是spring的ioc容器(父),一個是springmvc的ioc容器(子),這兩個容器是父子關系。這樣就會造成onApplicationEvent方法被執行兩次。為了解決此問題,我們可以判斷當前容器是否父容器,是父容器才執行下邊的代碼。步驟如下:通過參數contextRefreshedEvent獲取容器對象,在根據容器對象獲取其父容器,如果父容器為空,則說明當前容器是父容器。
@Component public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Autowired private ApplicationContext applicationContext; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { ApplicationContext parent = contextRefreshedEvent.getApplicationContext().getParent(); if (parent == null){ System.out.println("容器初始化完成。。。。。。。。"); } } }
