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