場景:
在代碼中需要動態獲取其它bean
實例代碼:
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容器,以訪問容器中定義的其他bean |
10 | public class SpringContextUtil implements ApplicationContextAware { |
13 | private static ApplicationContext applicationContext; |
16 | * 實現ApplicationContextAware接口的回調方法,設置上下文環境 |
18 | public void setApplicationContext(ApplicationContext applicationContext) |
19 | throws BeansException { |
20 | SpringContextUtil.applicationContext = applicationContext; |
23 | public static ApplicationContext getApplicationContext() { |
24 | return applicationContext; |
28 | * 獲取對象 這里重寫了bean方法,起主要作用 |
31 | * <a class="referer" target="_blank">@return</a> Object 一個以所給名字注冊的bean的實例 |
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、實現了ApplicationContextAware接口,在Bean的實例化時會自動調用setApplicationContext()方法!
2、通過調用靜態方法getBean即可獲取
|