1. 程式人生 > >獲取spring的ApplicationContext幾種方式【轉】

獲取spring的ApplicationContext幾種方式【轉】

throw 不能 在服務器 tap sync gconf 總結 title imp

轉自:http://blog.sina.com.cn/s/blog_9c7ba64d0101evar.html

Java類獲取spring 容器的bean

常用的5種獲取spring 中bean的方式總結:

方法一:在初始化時保存ApplicationContext對象

代碼:

1 ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
2 ac.getBean("beanId");

說明:這種方式適用於采用Spring框架的獨立應用程序,需要程序通過配置文件手工初始化Spring的情況。



方法二:通過Spring提供的工具類獲取ApplicationContext對象
代碼:

1 import org.springframework.web.context.support.WebApplicationContextUtils;
2 ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
3 ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
4 ac1.getBean("beanId"); 5 ac2.getBean("beanId");

說明:這種方式適合於采用Spring框架的B/S系統,通過ServletContext對象獲取ApplicationContext對象,然後在通過它獲取需要的類實例。

上面兩個工具方式的區別是,前者在獲取失敗時拋出異常,後者返回null。

方法三:繼承自抽象類ApplicationObjectSupport
說明:抽象類ApplicationObjectSupport提供getApplicationContext()方法,可以方便的獲取到ApplicationContext。
Spring初始化時,會通過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 對象註入。



方法四:繼承自抽象類WebApplicationObjectSupport
說明:類似上面方法,調用getWebApplicationContext()獲取WebApplicationContext

方法五:實現接口ApplicationContextAware
說明:實現該接口的setApplicationContext(ApplicationContext context)方法,並保存ApplicationContext 對象。
Spring初始化時,會通過該方法將ApplicationContext對象註入。

雖 然,spring提供了後三種方法可以實現在普通的類中繼承或實現相應的類或接口來獲取spring 的ApplicationContext對象,但是在使用是一定要註意實現了這些類或接口的普通java類一定要在Spring 的配置文件application-context.xml文件中進行配置。否則獲取的ApplicationContext對象將為null。



如下是我實現了ApplicationContextAware接口的例子

 1 package quartz.util;
 2 
 3 import org.springframework.beans.BeansException;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.ApplicationContextAware;
 6 
 7 public class SpringConfigTool implements ApplicationContextAware{//extends ApplicationObjectSupport{
 8 
 9 private static ApplicationContext context = null;
10 private static SpringConfigTool stools = null;
11 public synchronized static SpringConfigTool init(){
12   if(stools == null){
13    stools = new SpringConfigTool();
14   }
15   return stools;
16 }
17 
18 public void setApplicationContext(ApplicationContext applicationContext)
19 throws BeansException {
20   context = applicationContext;
21 }
22 
23 public synchronized static Object getBean(String beanName) {
24   return context.getBean(beanName);
25 }
26 
27 }

XML文件中的配置信息

最後提供一種不依賴於servlet,不需要註入的方式
註意一點,在服務器啟動時,Spring容器初始化時,不能通過以下方法獲取Spring 容器,如需細節可以觀看源碼

1 org.springframework.web.context.ContextLoader
2 
3 Title1 import org.springframework.web.context.ContextLoader; 
4 import org.springframework.web.context.WebApplicationContext; 
5  
6 WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); 
7   wac.getBean(beanID);

獲取spring的ApplicationContext幾種方式【轉】