本文研究的主要是Spring啟動后獲取所有擁有特定注解的Bean,具體如下。
最近項目中遇到一個業務場景,就是在Spring容器啟動后獲取所有的Bean中實現了一個特定接口的對象,第一個想到的是ApplicationContextAware,在setApplicationContext中去通過ctx獲取所有的bean,后來發現好像邏輯不對,這個方法不是在所有bean初始化完成后實現的,后來試了一下看看有沒有什么Listener之類的,發現了好東西ApplicationListener,然后百度一下ApplicationListener用法,原來有一大堆例子,我也記錄一下我的例子好了。
很簡單,只要實現ApplicationListener<ContextRefreshedEvent>
接口,然后把實現類進行@Component即可,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@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()); } } } |
其中,通過event.getApplicationContext().getBeansWithAnnotation
獲取到所有擁有特定注解的Beans集合,然后遍歷所有bean實現業務場景。
總結思考:這樣的功能可以實現系統參數的初始化,獲取系統中所有接口服務清單等一系列需要在Spring啟動后初始化的功能。
延生一下:除了以上啟動后事件外,還有其他三個事件
Closed在關閉容器的時候調用,Started理論上在容器啟動的時候調用,Stopped理論上在容器關閉的時候調用。
我通過TomcatServer進行啟動停止,只看到了Refreshed和Closed,不知道為啥,有空再繼續研究
總結
以上就是本文關于Spring啟動后獲取所有擁有特定注解的Bean實例代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/joshua1830/article/details/52117250