獲取Spring上下文(ApplicationContext)的三種方法


1.通過WebApplicationUtils工具類獲取,使用該方法的必須依賴Servlet容器。 方法如下:

ApplicationContext ap = WebApplicationUtils.getWebApplicationContext(servletContextParam)

其中servletContextParam是你需要傳入的Servlet容器參數。

 

2. 通過ClassPathXmlApplicationContext類獲取。

ApplicationContext ap = new ClassPathXmlApplicationContext("applicationContext.xml");

 

3.創建一個自己的工具類(SpringContextUtil)實現Spring的ApplicationContextAware接口。最后在Spring配置文件中注冊你的工具類。配置如下:

<bean id="springContextUtil" class="com.fubo.utils.spring.SpringContextUtil" lazy-init="false"/>

SpringContextUtil實現代碼如下:

 1 public class SpringContextUtil implements ApplicationContextAware {
 2     private static ApplicationContext applicationContext;
 3 
 4     /**
 5      * 實現ApplicationContextAware接口的setApplicationContext注入函數, 將其存入靜態變量.
 6      */
 7     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
 8         SpringContextUtil.applicationContext = applicationContext;
 9     }
10     /**
11      * 取得存儲在靜態變量中的ApplicationContext.
12      */
13     public static ApplicationContext getApplicationContext() {
14         checkApplicationContext();
15         return applicationContext;
16     }
17 
18     /**
19      * 從靜態變量ApplicationContext中取得Bean, 自動轉型為所賦值對象的類型.
20      */
21     @SuppressWarnings("unchecked")
22     public static <T> T getBean(String beanName){
23         checkApplicationContext();
24         return (T) applicationContext.getBean(beanName);
25     }
26     /**
27      * 清除applicationContext靜態變量.
28      */
29     public static void cleanApplicationContext(){
30         applicationContext = null;
31     }
32     private static void checkApplicationContext(){
33         if (applicationContext == null){
34             throw new IllegalStateException("applicationContext未注入,請在daos.xml中定義SpringContextUtil");
35         }
36     }
37 
38 }

 

總結:方式1要依賴Servlet容器,方式2實際只適合測試使用,方式1,2都有明顯弊端。建議使用方式3。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM