Spring啓動後獲取所有擁有特定註解的Bean

最近項目中遇到一個業務場景,就是在Spring容器啓動後獲取所有的Bean中實現了一個特定接口的對象,第一個想到的是ApplicationContextAware,在setApplicationContext中去通過ctx獲取所有的bean,後來發現好像邏輯不對,這個方法不是在所有bean初始化完成後實現的,後來試了一下看看有沒有什麼Listener之類的,發現了好東西ApplicationListener,然後百度一下ApplicationListener用法,原來有一大堆例子,我也記錄一下我的例子好了。

很簡單,只要實現ApplicationListener<ContextRefreshedEvent>接口,然後把實現類進行@Component即可,代碼如下:

Java代碼  收藏代碼
  1. <span style="font-size: 16px;">@Component  
  2. public class ContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {  
  3.   
  4.     @Override  
  5.     public void onApplicationEvent(ContextRefreshedEvent event) {  
  6.         // 根容器爲Spring容器  
  7.         if(event.getApplicationContext().getParent()==null){  
  8.             Map<String,Object> beans = event.getApplicationContext().getBeansWithAnnotation(IMobile.class);  
  9.             for(Object bean:beans.values()){  
  10.                 System.err.println(bean==null?"null":bean.getClass().getName());  
  11.             }  
  12.             System.err.println("=====ContextRefreshedEvent====="+event.getSource().getClass().getName());  
  13.         }  
  14.     }  
  15. }</span>  

 其中,通過event.getApplicationContext().getBeansWithAnnotation獲取到所有擁有特定註解的Beans集合,然後遍歷所有bean實現業務場景。

總結思考:這樣的功能可以實現系統參數的初始化,獲取系統中所有接口服務清單等一系列需要在Spring啓動後初始化的功能。

 

延生一下:除了以上啓動後事件外,還有其他三個事件

Closed在關閉容器的時候調用,

Started理論上在容器啓動的時候調用,

Stopped理論上在容器關閉的時候調用。

我通過TomcatServer進行啓動停止,只看到了Refreshed和Closed,不知道爲啥,有空再繼續研究


原文 http://fanyc.iteye.com/blog/2224809

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章