javascript
spring之:XmlWebApplicationContext作为Spring Web应用的IoC容器,实例化和加载Bean的过程...
它既是 DispatcherServlet 的 (WebApplicationContext)默認策略,又是 ContextLoaderListener 創建 root WebApplicationContext(根容器,同時也是 DispatcherServlet 的 WebApplicationContext 的父容器)的默認策略。
繼承體系
一、XmlWebApplicationContext實例化過程
spring的配置文件加載是以監聽的方式加載的xml配置文件
spring-web-4.3.14.RELEASE.jar中的org.springframework.web.context.ContextLoader.java類,通過ContextLoader初始化和銷毀Spring Web上下文的過程。
1、ContextLoader類中有一個靜態代碼塊,這個靜態代碼塊就是從配置中讀取到“XmlWebApplicationContext”類
"contextLoader.properties"文件就在ContextLoader.class的相同目錄中,
contextLoader.properties:(配置中配置的就是XmlWebApplicationContext)
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext2、上面只是將配置讀取到ContextLoader中,下面看看XmlWebApplicationContext怎么初始化的,ContextLoader.initWebApplicationContext方法:
org.springframework.web.context.ContextLoader.java
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {//檢查是否已經創建了Application context,如果已經存在,拋異常退出if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this.context == null) { //調用createWebApplicationContext,創建XmlWebApplicationContext, this.context = createWebApplicationContext(servletContext); } // 如果當前的應用上下文對象是 ConfigurableWebApplicationContext if (this.context instanceof ConfigurableWebApplicationContext) { //強制類型轉換 ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; // 如果應用上下文沒有生效 if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc 如果該上下文對象為nul if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. //加載父上下文 ApplicationContext parent = loadParentContext(servletContext); // 設置父上下文 cwac.setParent(parent); } configureAndRefreshWebApplicationContext(cwac, servletContext); } } //將該上下文對象放入servlet上下文參數中servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); //獲取當前線程的類加載器 ClassLoader ccl = Thread.currentThread().getContextClassLoader(); // 如果ContextLoader的類加載器和當前線程的類加載器一樣,則應用上下文對象賦值給currentContext if (ccl == ContextLoader.class.getClassLoader()) { currentContext = this.context; } //否則,就將ContextLoader的類加載器放入到Map中,Map的value是應用上下文對象 else if (ccl != null) { currentContextPerThread.put(ccl, this.context); } if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } //最后返回應用上下文對象 return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } }
在ContextLoader.createWebApplicationContext方法中
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {//獲取上下文類Class<?> contextClass = determineContextClass(sc);//如果該上下文類沒有實現ConfigurableWebApplicationContext接口則拋出異常 if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {throw new ApplicationContextException("Custom context class [" + contextClass.getName() +"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");}// 返回該上下文類的實例,調用BeanUtils.instantiateClass(contextClass),通過反射,調用XmlWebApplicationContext的無參構造函數實例化XmlWebApplicationContext對象return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);}----------------------------BeanUtils.instantiateClass()-----------------------------------------------------------------------------------------------------------------------
這里插入BeanUtils.instantiateClass(),BeanUtils使用instantiateClass初始化對象注意:必須保證初始化類必須有public默認無參數構造器,注意初始化內部類時,內部類必須是靜態的,否則報錯!
public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException {Assert.notNull(clazz, "Class must not be null");if (clazz.isInterface()) {throw new BeanInstantiationException(clazz, "Specified class is an interface");}try {return instantiateClass(clazz.getDeclaredConstructor());}catch (NoSuchMethodException ex) {throw new BeanInstantiationException(clazz, "No default constructor found", ex);}}public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {Assert.notNull(ctor, "Constructor must not be null");try {ReflectionUtils.makeAccessible(ctor);return ctor.newInstance(args);}//... }@CallerSensitivepublic T newInstance(Object ... initargs)throws InstantiationException, IllegalAccessException,IllegalArgumentException, InvocationTargetException{if (!override) {if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {Class<?> caller = Reflection.getCallerClass();checkAccess(caller, clazz, null, modifiers);}}if ((clazz.getModifiers() & Modifier.ENUM) != 0)throw new IllegalArgumentException("Cannot reflectively create enum objects");ConstructorAccessor ca = constructorAccessor; // read volatileif (ca == null) {ca = acquireConstructorAccessor();}@SuppressWarnings("unchecked")T inst = (T) ca.newInstance(initargs);return inst;}----------------------------BeanUtils.instantiateClass()-----------------------------------------------------------------------------------------------------------------------
ContextLoader.java中的determineContextClass()方法:
/*** 返回上下文類型*/protected Class<?> determineContextClass(ServletContext servletContext) {//從servlet上下文中獲取初始化配置參數contextClass的值String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);// 如果contextClassName不為null則放回配置的Class對象if (contextClassName != null) {try {return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());}catch (ClassNotFoundException ex) {throw new ApplicationContextException("Failed to load custom context class [" + contextClassName + "]", ex);}}else {// 如果沒有配置則使用XmlWebApplicationContext,這個代碼就是從contextLoad.properties配置中加載進來的,配置中的就是XmlWebApplicationContextcontextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());try {return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());}catch (ClassNotFoundException ex) {throw new ApplicationContextException("Failed to load default context class [" + contextClassName + "]", ex);}}}在Spring web項目中XmlWebApplicationContext是如何創建的?
首先在web.xml中我們可以看到如下配置:
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:META-INF/spring/*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>ContextLoaderListener繼承Spring的ContextLoader上下文加載器類,同時實現ServletContextListener接口(Servlet上下文監聽器),監聽Web服務器上下文的啟動和停止事件,管理Web環境中Spring的啟動和銷毀過程,
首先我們看看這個監聽器的源碼。初始化的入口是contextInitialized方法,它只是簡單地將初始化功能委托為了ContextLoader進行處理。
org.springframework.web.context.ContextLoaderListener.java
/*** Initialize the root web application context.初始化根WEB應用上下文*/@Overridepublic void contextInitialized(ServletContextEvent event) {initWebApplicationContext(event.getServletContext()); //調用ContextLoader的initWebApplicationContext()}通過對ContextLoaderListener的源碼分析,我們看到ContextLoaderListener繼承ContextLoader,所以ContextLoaderListener本身也是Spring的上下文加載器。
ContextLoaderListener實現了ServletContextListener接口,當Web應用在Web服務器中被被啟動和停止時,Web服務器啟動和停止事件會分別觸發ContextLoaderListener的contextInitialized和contextDestroyed方法來初始化和銷毀Spring上下文。我們通過上述對ContextLoaderListener的源碼分析看到真正實現Spring上下文的初始化和銷毀功能的是ContextLoader類,分析ContextLoader初始化和銷毀Spring Web上下文的過程見上面。
?ContextLoader的initWebApplicationContext()的源碼見上面的分析。
在springmvc中,如何實例化XmlWebApplicationContext的?
1、springmvc加載配置文件
org.springframework.web.servlet.DispatcherServlet是通過這個servlet,加載配置文件
FrameworkServlet中有一個屬性
接著看FrameworkServlet的initWebApplicationContext()方法:
protected WebApplicationContext initWebApplicationContext() { .....if (wac == null) {// No context instance is defined for this servlet -> create a local onewac = createWebApplicationContext(rootContext);} }?方法中有一個FrameworkServlet.createWebApplicationContext(rootContext)方法
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {//這個方法就是創建XmlWebApplicationContext實例的ClassClass<?> contextClass = getContextClass();if (this.logger.isDebugEnabled()) {this.logger.debug("Servlet with name '" + getServletName() +"' will try to create custom WebApplicationContext context of class '" +contextClass.getName() + "'" + ", using parent context [" + parent + "]");}//如果該上下文類沒有實現ConfigurableWebApplicationContext接口則拋出異常 if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {throw new ApplicationContextException("Fatal initialization error in servlet with name '" + getServletName() +"': custom WebApplicationContext class [" + contextClass.getName() +"] is not of type ConfigurableWebApplicationContext");}
//調用BeanUtils.instantiateClass(contextClass),通過反射,調用XmlWebApplicationContext的無參構造函數實例化XmlWebApplicationContext對象ConfigurableWebApplicationContext wac =(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);wac.setEnvironment(getEnvironment());wac.setParent(parent);wac.setConfigLocation(getContextConfigLocation());configureAndRefreshWebApplicationContext(wac);return wac; }
接口看getContextClass()方法:
Class<?> contextClass = getContextClass();這個方法就是創建XmlWebApplicationContext實例的Class
public Class<?> getContextClass() {return this.contextClass;}?this.contextClass就是前面FrameworkServlet定義的全局變量。
至此,實例化XmlWebApplicationContext的步驟基本相同:
1、通過讀取配置文件方式,讀取到org.springframework.web.context.WebApplicationContext的類型為“org.springframework.web.context.support.XmlWebApplicationContext”;
2、檢查上下文類沒有實現ConfigurableWebApplicationContext接口則拋出異常;
3、調用BeanUtils.instantiateClass(contextClass),通過反射,調用XmlWebApplicationContext的無參構造函數實例化XmlWebApplicationContext對象;
二、XmlWebApplicationContext源碼
ContextLoader初始化Spring Web上下文的determineContextClass方法中,我們知道Spring首先通過Servlet上下文從web.xml文件中獲取用戶自定義配置的contextClass參數值,如果沒有獲取到,則默認使用Spring的XmlWebApplicationContext作為Spring Web應用的IoC容器,XmlWebApplicationContext是WebApplicationContext的實現類ConfigurableWebApplicationContext的子類
public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {//Web應用中Spring配置文件的默認位置和名稱,如果沒有特別指定,則Spring會根據//此位置定義Spring Bean定義資源public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";//Spring Bean定義資源默認前綴public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";//Spring Bean定義資源默認后置public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";//在分析Spring IoC初始化過程中我們已經分析過,加載Spring Bean定義資源的方法,//通過Spring容器刷新的refresh()方法觸發protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {//為Spring容器創建XML Bean定義讀取器,加載Spring Bean定義資源XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);// resource loading environment. beanDefinitionReader.setEnvironment(getEnvironment());//設置Bean定義讀取器,因為XmlWebApplicationContext是DefaultResourceLoader的子類,所以使用默認資源加載器來定義Bean定義資源beanDefinitionReader.setResourceLoader(this);//為Bean定義讀取器設置SAX實體解析器beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));//在加載Bean定義之前,調用子類提供的一些用戶自定義初始化Bean定義讀取器的方法 initBeanDefinitionReader(beanDefinitionReader);//使用Bean定義讀取器加載Bean定義資源 loadBeanDefinitions(beanDefinitionReader);}//用戶自定義初始化Bean定義讀取器的方法protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {}//加載Bean定義資源protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {//獲取定位的Bean定義資源路徑String[] configLocations = getConfigLocations();if (configLocations != null) {//遍歷加載所有定義的Bean定義資源for (String configLocation : configLocations) {reader.loadBeanDefinitions(configLocation);}}}//獲取默認Bean定義資源protected String[] getDefaultConfigLocations() {//獲取web.xml中的命名空間,如命名空間不為null,則返回 “/WEB-INF/命名空間.xml”if (getNamespace() != null) {return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX};}//如果命名空間為null,則返回"/WEB-INF/applicationContext.xml"else {return new String[] {DEFAULT_CONFIG_LOCATION};}} }XmlWebApplicationContext將Web應用中配置的Spring Bean定義資源文件載入到Spring IoC容器中后,接下來的Spring IoC容器初始化和依賴注入的過程后面再分析。
?
轉載于:https://www.cnblogs.com/duanxz/p/3507449.html
總結
以上是生活随笔為你收集整理的spring之:XmlWebApplicationContext作为Spring Web应用的IoC容器,实例化和加载Bean的过程...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 密码破解—Hashcat
- 下一篇: JavaScript(js)的repla