天天看點

spring容器在web.xml中的初始化加載

spring通過xml配置加載XMLApplicationContext容器環境,在web.xml中有兩種配置方法:

方法1,通過ContextLoaderListener加載spring容器

<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:web-servlet.xml,classpath:common-servlet.xml,classpath:openapi-servlet.xml,classpath:aliyunid-service.xml</param-value> </context-param> <servlet> <servlet-name>aliyunid</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextAttribute</param-name> <param-value>org.springframework.web.context.WebApplicationContext.ROOT</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>

方法2,在DispatcherServlet内部配置spring的配置檔案路徑,加載容器

<servlet> <servlet-name>aliyunid</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:web-servlet.xml,classpath:common-servlet.xml,classpath:openapi-servlet.xml,classpath:aliyunid-service.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>

ContextLoaderListener在ServletContext會先于Servlet加載。加載後,會通過讀取contextConfigLocation變量獲得spring xml配置檔案的路徑,然後執行個體化XMLApplictionContext類型的spring容器。并将其作為servletContext.setAttribute,塞入servlet容器中。key為:ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";

DispatcherServlet作為請求的分發入口,其父類FrameworkServlet首先根據contextAttribute配置值作為key,去servletContext中查找ApplicationContext的容器對象。如果找到,則直接使用。

如果沒有找到或者未設定contextAttribute屬性,則從contextConfigLocation中讀取xml配置檔案的位址,預設為 /WEB-INF/getServletName() + "-servlet.xml" 作為配置檔案位址,進行容器的初始化。以 WebApplicationContext.class.getName() + ".ROOT" 作為key從servletContext中查找spring容器對象,并以此對象作為前者的parent。