最近項目中遇到一個業務場景,就是在Spring容器啓動後獲取所有的Bean中實現了一個特定接口的對象,第一個想到的是ApplicationContextAware,在setApplicationContext中去通過ctx獲取所有的bean,後來發現好像邏輯不對,這個方法不是在所有bean初始化完成後實現的,後來試了一下看看有沒有什麼Listener之類的,發現了好東西ApplicationListener,然後百度一下ApplicationListener用法,原來有一大堆例子,我也記錄一下我的例子好了。
很簡單,只要實現ApplicationListener<ContextRefreshedEvent>接口,然後把實現類進行@Component即可,代碼如下:
- <span style="font-size: 16px;">@Component
- public class ContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {
- @Override
- public void onApplicationEvent(ContextRefreshedEvent event) {
- // 根容器爲Spring容器
- if(event.getApplicationContext().getParent()==null){
- Map<String,Object> beans = event.getApplicationContext().getBeansWithAnnotation(IMobile.class);
- for(Object bean:beans.values()){
- System.err.println(bean==null?"null":bean.getClass().getName());
- }
- System.err.println("=====ContextRefreshedEvent====="+event.getSource().getClass().getName());
- }
- }
- }</span>
其中,通過event.getApplicationContext().getBeansWithAnnotation獲取到所有擁有特定註解的Beans集合,然後遍歷所有bean實現業務場景。
總結思考:這樣的功能可以實現系統參數的初始化,獲取系統中所有接口服務清單等一系列需要在Spring啓動後初始化的功能。
延生一下:除了以上啓動後事件外,還有其他三個事件
Closed在關閉容器的時候調用,
Started理論上在容器啓動的時候調用,
Stopped理論上在容器關閉的時候調用。
我通過TomcatServer進行啓動停止,只看到了Refreshed和Closed,不知道爲啥,有空再繼續研究
原文 http://fanyc.iteye.com/blog/2224809