標籤:ack 擷取 zed 初始化 方式 str ini 執行個體 調用
轉自: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.ContextLoader2 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幾種方式【轉】