場(chǎng)景:
在代碼中需要?jiǎng)討B(tài)獲取其它bean
實(shí)例代碼:
01 | package org.company.xxx; |
03 | import org.springframework.beans.BeansException; |
04 | import org.springframework.context.ApplicationContext; |
05 | import org.springframework.context.ApplicationContextAware; |
08 | * 獲取spring容器,以訪問(wèn)容器中定義的其他bean |
10 | public class SpringContextUtil implements ApplicationContextAware { |
13 | private static ApplicationContext applicationContext; |
16 | * 實(shí)現(xiàn)ApplicationContextAware接口的回調(diào)方法,設(shè)置上下文環(huán)境 |
18 | public void setApplicationContext(ApplicationContext applicationContext) |
19 | throws BeansException { |
20 | SpringContextUtil.applicationContext = applicationContext; |
23 | public static ApplicationContext getApplicationContext() { |
24 | return applicationContext; |
28 | * 獲取對(duì)象 這里重寫了bean方法,起主要作用 |
31 | * <a class="referer" target="_blank">@return</a> Object 一個(gè)以所給名字注冊(cè)的bean的實(shí)例 |
32 | * @throws BeansException |
34 | public static Object getBean(String beanId) throws BeansException { |
35 | return applicationContext.getBean(beanId); |
Bean配置:
1 | < beanid = "SpringContextUtil" class = "org.company.xxx.SpringContextUtil" /> |
注:
1、實(shí)現(xiàn)了ApplicationContextAware接口,在Bean的實(shí)例化時(shí)會(huì)自動(dòng)調(diào)用setApplicationContext()方法!
2、通過(guò)調(diào)用靜態(tài)方法getBean即可獲取
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。