spring容器的啟動(dòng)過(guò)程是什么偷拔?
spring在web容器中蟀瞧,啟動(dòng)過(guò)程是Servlet 容器對(duì)spring環(huán)境的構(gòu)造,初始化条摸,裝配的過(guò)程。
spring的啟動(dòng)過(guò)程
1.通過(guò)ContextLoaderListener監(jiān)聽(tīng)作為啟動(dòng)spring的入口
啟動(dòng)必要條件:在web.xml中配置
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
ContextLoaderListener(spring中的類(lèi))繼承ContextLoader(spring中的類(lèi))铸屉,并實(shí)現(xiàn)ServletContextListener(servlet中的接口)钉蒲,ServletContextListener監(jiān)聽(tīng)ServletContext,當(dāng)容器啟動(dòng)時(shí)彻坛,會(huì)觸發(fā)ServletContextEvent事件顷啼,該事件由ServletContextListener來(lái)處理,啟動(dòng)初始化ServletContext時(shí)昌屉,調(diào)用contextInitialized方法钙蒙。而ContextLoaderListener實(shí)現(xiàn)了ServletContextListener,所以间驮,當(dāng)容器啟動(dòng)時(shí)躬厌,觸發(fā)ServletContextEvent事件,讓ContextLoaderListener執(zhí)行實(shí)現(xiàn)方法contextInitialized(ServletContextEvent sce);
這部分源碼為:
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
}
2.通過(guò)initWebApplicationContext方法來(lái)初始化WebApplicationContext
WebApplicationContext是spring中的上下文竞帽。它的作用等同于Servlet中的ServletContext扛施。
(部分注釋源碼被我刪掉)
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
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!");
}
try {
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
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;
}
}
initWebApplicationContext(ServletContext servletContext)方法是ContextLoader中的方法鸿捧。它的作用是制作一個(gè)WebApplicationContext上下文,并將這個(gè)上下文保存在servletContext中疙渣,并保存在當(dāng)前ContextLoader實(shí)例中匙奴。
3.如何初始化WebApplicationContext
上面源碼中的
this.context = createWebApplicationContext(servletContext);
用來(lái)制造一個(gè)WebApplicationContext,制造的過(guò)程妄荔,依賴ServletContext泼菌。
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
通過(guò)determineContextClass(ServletContext servletContext)方法獲取需要實(shí)例化的context類(lèi)的class,通過(guò)BeanUtils.instantiateClass(contextClass)將這個(gè)class用反射的手段實(shí)例化WebApplicationContext 啦租。
那么determineContextClass怎樣來(lái)確定實(shí)例化那個(gè)context類(lèi)那哗伯?(spring有很多的context類(lèi)實(shí)現(xiàn)了WebApplicationContext ,當(dāng)然這個(gè)context類(lèi)也可以是我們自己寫(xiě)的刷钢,具體實(shí)例化那個(gè)類(lèi)笋颤,在web.xml中配置)
protected Class<?> determineContextClass(ServletContext servletContext) {
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
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 {
contextClassName = 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);
}
}
}
從上面的代碼可以看出,先從servletContext中找我們?cè)趙eb.xml中有沒(méi)有配置要實(shí)例化那個(gè)上下文context内地,如果配置了
<context-param>
<param-name>contextClass</param-name>
<param-value>rg.springframework.web.context.support.StaticWebApplicationContext</param-value>
</context-param>
那么將實(shí)例化StaticWebApplicationContext這個(gè)上下文伴澄。注意:這個(gè)地方的param-name必須是contextClass(約定成俗的,其實(shí)就是是程序?qū)懰赖模┶寤骸H绻麤](méi)有這個(gè)配置非凌,那么程序?qū)⒄业揭粋€(gè)叫ContextLoader.properties的配置文件,這個(gè)配置文件注明了一個(gè)默認(rèn)的上下文:XmlWebApplicationContext荆针。這個(gè)XmlWebApplicationContext實(shí)例化的過(guò)程是制造一個(gè)ResourcePatternResolver的實(shí)例敞嗡,這個(gè)實(shí)例將會(huì)在后面的spring啟動(dòng)過(guò)程中起到關(guān)鍵作用。
最后流程圖: