方法一:在初始化時保存ApplicationContext對象
方法二:經過Spring提供的utils類獲取ApplicationContext對象
方法三:繼承自抽象類ApplicationObjectSupport
方法四:繼承自抽象類WebApplicationObjectSupport
方法五:實現接口ApplicationContextAware
方法六:經過Spring提供的ContextLoaderjava
獲取spring中bean的方式總結:
web
- ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
- ac.getBean("userService");//好比:<bean id="userService" class="com.cloud.service.impl.UserServiceImpl"></bean>
說明:這樣的方式適用於採用Spring框架的獨立應用程序,需要程序經過配置文件手工初始化Spring的狀況。spring
- ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
- ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
- ac1.getBean("beanId");
- ac2.getBean("beanId");
說明:這樣的方式適合於採用Spring框架的B/S系統,經過ServletContext對象獲取ApplicationContext對象。而後在經過它獲取需要的類實例。上面兩個工具方式的差異是,前者在獲取失敗時拋出異常。後者返回null。app
說明:抽象類ApplicationObjectSupport提供getApplicationContext()方法。可以方便的獲取ApplicationContext。框架
Spring初始化時。會經過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 對象注入。工具
說明:相似上面方法。調用getWebApplicationContext()獲取WebApplicationContextui
說明:實現該接口的setApplicationContext(ApplicationContext context)方法,並保存ApplicationContext 對象。Spring初始化時,會經過該方法將ApplicationContext對象注入。spa
下面是實現ApplicationContextAware接口方式的代碼,前面兩種方法相似:server
- public class SpringContextUtil implements ApplicationContextAware {
- // Spring應用上下文環境
- private static ApplicationContext applicationContext;
- /**
- * 實現ApplicationContextAware接口的回調方法。設置上下文環境
- *
- * @param applicationContext
- */
- public void setApplicationContext(ApplicationContext applicationContext) {
- SpringContextUtil.applicationContext = applicationContext;
- }
- /**
- * @return ApplicationContext
- */
- public static ApplicationContext getApplicationContext() {
- return applicationContext;
- }
- /**
- * 獲取對象
- *
- * @param name
- * @return Object
- * @throws BeansException
- */
- public static Object getBean(String name) throws BeansException {
- return applicationContext.getBean(name);
- }
- }
儘管,spring提供的後三種方法可以實現在普通的類中繼承或實現對應的類或接口來獲取spring 的ApplicationContext對象,但是在使用是必定要注意實現了這些類或接口的普通java類必定要在Spring 的配置文件applicationContext.xml文件裏進行配置。不然獲取的ApplicationContext對象將爲null。xml
- WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
- wac.getBean(beanID);
最後提供一種不依賴於servlet,不需要注入的方式。但是需要注意一點,在server啓動時。Spring容器初始化時,不能經過下面方法獲取Spring 容器,細節可以查看spring源代碼org.springframework.web.context.ContextLoader。