獲取spring上下文 - applicationContext


前言

  spring上下文是spring容器抽象的一種實現。將你需spring幫你管理的對象放入容器的一種對象,ApplicationContext是一維護Bean定義以及對象之間協作關第的高級接口。

獲取spring的上下文環境ApplicationContext的方式

一)、通過WebApplicationUtils工具類獲取。

  WebApplicationUtils類是在Spring框架基礎包spring-web-3.2.0. RELEASE.jar中的類。使用該方法的必須依賴Servlet容器。 使用方法如下: 

// Spring中獲取ServletContext對象,普通類中可以這樣獲取
ServletContext sc = ContextLoader.getCurrentWebApplicationContext().getServletContext(); // servlet中可以這樣獲取,方法比較多
ServletContext sc = request.getServletContext(): ServletContext sc = servletConfig.getServletContext();  //servletConfig可以在servlet的init(ServletConfig config)方法中獲取得到
 
/* 需要傳入一個參數ServletContext對象, 獲取方法在上面 */
// 這種方法 獲取失敗時拋出異常
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); // 這種方法 獲取失敗時返回null
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);

二)、通過加載 配置文件注解配置類 獲取

① ClassPathXmlApplicationContext:從類路徑下的一個或多個xml配置文件中加載上下文定義,適用於xml配置的方式; 這種測試常用

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

② FileSystemXmlApplicationContext:從文件系統下的一個或多個xml配置文件中加載上下文定義,也就是說系統盤符中加載xml配置文件;

③ XmlWebApplicationContext:從web應用下的一個或多個xml配置文件加載上下文定義,適用於xml配置方式。

④AnnotationConfigApplicationContext:從一個或多個基於java的配置類中加載上下文定義,適用於java注解的方式;

⑤ AnnotationConfigWebApplicationContext:專門為web應用准備的,適用於注解方式;

 三)、創建一個自己的工具類(SpringContextHolder)實現Spring的ApplicationContextAware接口。

 ① 在配置文件中注冊工具類

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

② 工具類

import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * 實現spring context的管理 */ @Component("applicationContextHelper") public class ApplicationContextHelper implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { applicationContext = context; }   //根據類型獲取bean public static <T> T popBean(Class<T> clazz){ checkApplicationContext(); return applicationContext.getBean(clazz); }    //根據名稱獲取bean public static <T> T popBean(String name){ checkApplicationContext(); return applicationContext.getBean(clazz); }    //根據名稱和類型獲取bean public static <T> T popBean(String name, Class<T> clazz){ checkApplicationContext(); return applicationContext.getBean(name, clazz); } //檢查applicationContext是否為空
    private static void checkApplicationContext(){ if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義SpringContextHolder"); } } }


免責聲明!

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



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