無聊在家看源碼,雖然沒看懂多少亡嫌,但是還是想紀(jì)錄一下嚎于,埋下一顆種子掘而。
有時(shí)候,一些問題于购,我總是想要追根尋底袍睡,一直搞的Web開發(fā),但是卻每次只能在Controller
層去編寫代碼肋僧,調(diào)試代碼斑胜,感覺心里總有些(其實(shí)是很)不爽,所以擅自超出自己的能力范圍嫌吠,去看了看Tomcat
和Servlet
和Spring
的源碼止潘,果然如我所料,的確是非常難居兆,所以覆山,只能記下一些關(guān)鍵點(diǎn),為以后留下點(diǎn)東西泥栖。
看了好久簇宽,直到最后,才發(fā)現(xiàn)這個(gè)關(guān)鍵點(diǎn)吧享,如下圖所示魏割。
發(fā)現(xiàn)沒有,這里是三個(gè)包之間的交互點(diǎn)钢颂,從這三條堆棧的運(yùn)行來看钞它,就可以看到這三個(gè)關(guān)鍵點(diǎn)之間是如何交互的。
那么一個(gè)一個(gè)函數(shù)來看殊鞭。
private synchronized void initServlet(Servlet servlet) throws ServletException {
if(!this.instanceInitialized || this.singleThreadModel) {
try {
this.instanceSupport.fireInstanceEvent("beforeInit", servlet);
if(Globals.IS_SECURITY_ENABLED) {
boolean f = false;
try {
Object[] args = new Object[]{this.facade};
SecurityUtil.doAsPrivilege("init", servlet, classType, args);
f = true;
} finally {
if(!f) {
SecurityUtil.remove(servlet);
}
}
} else {
servlet.init(this.facade);
}
this.instanceInitialized = true;
this.instanceSupport.fireInstanceEvent("afterInit", servlet);
} catch (UnavailableException var10) {
this.instanceSupport.fireInstanceEvent("afterInit", servlet, var10);
this.unavailable(var10);
throw var10;
} catch (ServletException var11) {
this.instanceSupport.fireInstanceEvent("afterInit", servlet, var11);
throw var11;
} catch (Throwable var12) {
ExceptionUtils.handleThrowable(var12);
this.getServletContext().log("StandardWrapper.Throwable", var12);
this.instanceSupport.fireInstanceEvent("afterInit", servlet, var12);
throw new ServletException(sm.getString("standardWrapper.initException", new Object[]{this.getName()}), var12);
}
}
}
這個(gè)就是Tomcat的那條堆棧的函數(shù)遭垛。看到很多blog
都很空泛的說操灿,Web容器
會(huì)加載web.xml
的內(nèi)容锯仪,然后加載里面定義的Servlet
,之后會(huì)調(diào)用init()
的內(nèi)容,但是都沒有代碼級別的示例趾盐,這讓我著實(shí)心癢庶喜。所以想盡辦法來窺的一絲一毫。
這里函數(shù)里面其實(shí)已經(jīng)加載好了Servlet
,如果在Idea
里面把鼠標(biāo)移動(dòng)到Servlet
上面可以看到類型就是我在web.xml
里面配置的DispatherServlet
的實(shí)例救鲤。
關(guān)鍵代碼就是Servlet.init(this.facade)
久窟。也就是這里Tomcat
調(diào)用Servlet
的init()
函數(shù)。這邊也應(yīng)該要注意到的是參數(shù)this.facade
本缠,沒錯(cuò),這個(gè)就是Servlet
接口中的init(ServletConfig config)
的config
參數(shù)斥扛,里面最重要的就是給了Servlet
一個(gè)ServletContext
的引用,這樣每個(gè)Servlet
就可以訪問到唯一的一個(gè)ServletContext
丹锹。
下面的是Servlet
的接口源代碼犹赖。
package javax.servlet;
import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
public GenericServlet() {
}
public void destroy() {
}
public ServletConfig getServletConfig() {
return this.config;
}
public ServletContext getServletContext() {
return this.getServletConfig().getServletContext();
}
public String getServletInfo() {
return "";
}
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init() throws ServletException {
}
public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
}
從接口中可以更加明顯的看到config
賦值行為队他。之后又接著調(diào)用了沒有參數(shù)的init()
函數(shù)。之后就是Spring
的有個(gè)HttpServletBean
的類進(jìn)行了init()
函數(shù)的實(shí)現(xiàn)峻村。具體源代碼如下。
public final void init() throws ServletException {
if(this.logger.isDebugEnabled()) {
this.logger.debug("Initializing servlet \'" + this.getServletName() + "\'");
}
try {
HttpServletBean.ServletConfigPropertyValues ex = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ServletContextResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment()));
this.initBeanWrapper(bw);
bw.setPropertyValues(ex, true);
} catch (BeansException var4) {
this.logger.error("Failed to set bean properties on servlet \'" + this.getServletName() + "\'", var4);
throw var4;
}
this.initServletBean();
if(this.logger.isDebugEnabled()) {
this.logger.debug("Servlet \'" + this.getServletName() + "\' configured successfully");
}
}
從這個(gè)函數(shù)開始就沒有Tomcat
的什么事情了锡凝,就開始進(jìn)入到Spring
的管理中來了粘昨。
好的,下面雖然看的不是很懂了窜锯,但是能走幾步就走幾步张肾。
按照調(diào)用棧的過程,可以看到之后是FrameworkServlet
的initServletBean
的調(diào)用锚扎。這回先上代碼吞瞪。
protected final void initServletBean() throws ServletException {
this.getServletContext().log("Initializing Spring FrameworkServlet \'" + this.getServletName() + "\'");
if(this.logger.isInfoEnabled()) {
this.logger.info("FrameworkServlet \'" + this.getServletName() + "\': initialization started");
}
long startTime = System.currentTimeMillis();
try {
//開始初始化前端控制器自己的Bean容器
this.webApplicationContext = this.initWebApplicationContext();
this.initFrameworkServlet();
} catch (ServletException var5) {
this.logger.error("Context initialization failed", var5);
throw var5;
} catch (RuntimeException var6) {
this.logger.error("Context initialization failed", var6);
throw var6;
}
if(this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet \'" + this.getServletName() + "\': initialization completed in " + elapsedTime + " ms");
}
}
從代碼中可以看到最先做的事情是初始化了DispatherServlet
自己的Bean
容器,好驾孔,在進(jìn)入這個(gè)初始的代碼看看芍秆,又做了一些什么事情呢。
protected WebApplicationContext initWebApplicationContext() {
//先嘗試從ServletContext中獲得全局的Spring容器
//全局的Spring容器是通過監(jiān)聽器獲得的翠勉,但是我這里沒有配置
//所以返回的是個(gè)null妖啥,rootContext=null
WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
WebApplicationContext wac = null;
//分為兩種情況,一種是Bean容器已存在(什么情況下會(huì)這樣呢?)
if(this.webApplicationContext != null) {
wac = this.webApplicationContext;
if(wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext attrName = (ConfigurableWebApplicationContext)wac;
if(!attrName.isActive()) {
if(attrName.getParent() == null) {
attrName.setParent(rootContext);
}
//最后調(diào)用這個(gè)配置和刷新Bean容器
//如果是下面一個(gè)創(chuàng)建的分支的話对碌,最后也是會(huì)執(zhí)行這個(gè)函數(shù)的
this.configureAndRefreshWebApplicationContext(attrName);
}
}
}
//如果沒有初始化荆虱,第一次進(jìn)來的時(shí)候一定是沒有初始化的
//找一下?怎么找?
if(wac == null) {
wac = this.findWebApplicationContext();
}
//找不到就造一個(gè),實(shí)例化一個(gè)
if(wac == null) {
wac = this.createWebApplicationContext(rootContext);
}
if(!this.refreshEventReceived) {
this.onRefresh(wac);
}
if(this.publishContext) {
String attrName1 = this.getServletContextAttributeName();
this.getServletContext().setAttribute(attrName1, wac);
if(this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet \'" + this.getServletName() + "\' as ServletContext attribute with name [" + attrName1 + "]");
}
}
return wac;
}
在走兩步到FrameServlet
的createWebApplicationContext
這里朽们。有個(gè)關(guān)鍵一個(gè)是把從ServletContext
中獲得原始的Bean容器作為了DispatherServlet
自己的父容器了怀读。
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
Class contextClass = this.getContextClass();
if(this.logger.isDebugEnabled()) {
this.logger.debug("Servlet with name \'" + this.getServletName() + "\' will try to create custom WebApplicationContext context of class \'" + contextClass.getName() + "\'" + ", using parent context [" + parent + "]");
}
if(!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Fatal initialization error in servlet with name \'" + this.getServletName() + "\': custom WebApplicationContext class [" + contextClass.getName() + "] is not of type ConfigurableWebApplicationContext");
} else {
ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(this.getEnvironment());
//將從監(jiān)聽器獲得的Spring容器作為父容器
wac.setParent(parent);
wac.setConfigLocation(this.getContextConfigLocation());
//調(diào)用這個(gè)配置和刷新Web應(yīng)用上下文的函數(shù)
this.configureAndRefreshWebApplicationContext(wac);
return wac;
}
}
好,接著看骑脱。
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
if(ObjectUtils.identityToString(wac).equals(wac.getId())) {
if(this.contextId != null) {
wac.setId(this.contextId);
} else {
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(this.getServletContext().getContextPath()) + "/" + this.getServletName());
}
}
wac.setServletContext(this.getServletContext());
wac.setServletConfig(this.getServletConfig());
wac.setNamespace(this.getNamespace());
wac.addApplicationListener(new SourceFilteringListener(wac, new FrameworkServlet.ContextRefreshListener(null)));
ConfigurableEnvironment env = wac.getEnvironment();
if(env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment)env).initPropertySources(this.getServletContext(), this.getServletConfig());
}
this.postProcessWebApplicationContext(wac);
this.applyInitializers(wac);
//上面都是把一些ServletContext和ServletConfig之類的設(shè)置進(jìn)入Web應(yīng)用上下菜枷,下面是refresh()
wac.refresh();
}
再進(jìn)入到refresh()
函數(shù)中,md惜姐,完全沒看懂犁跪,逃...
public void refresh() throws BeansException, IllegalStateException {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
//以上都不知道在干啥了
this.finishRefresh();
} catch (BeansException var5) {
this.destroyBeans();
this.cancelRefresh(var5);
throw var5;
}
}
}
中間跳過無數(shù)看不懂的東西,好像是一些事件傳遞歹袁,監(jiān)聽坷衍,委托之類的,最后終于調(diào)用了DispatherServlet
的onRefresh
函數(shù)和initStrategies
函數(shù)条舔。但是其實(shí)在DispatherServlet
被Tomcat
初始化的時(shí)候會(huì)先調(diào)用DiapatherServlet
的靜態(tài)區(qū)塊枫耳,之后才是無參構(gòu)造函數(shù)。
protected void onRefresh(ApplicationContext context) {
this.initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
this.initMultipartResolver(context);
this.initLocaleResolver(context);
this.initThemeResolver(context);
this.initHandlerMappings(context);
this.initHandlerAdapters(context);
this.initHandlerExceptionResolvers(context);
this.initRequestToViewNameTranslator(context);
this.initViewResolvers(context);
this.initFlashMapManager(context);
}
再補(bǔ)上我這個(gè)Debug
項(xiàng)目的web.xml
文件孟抗。
<?xml version="1.0" encoding="UTF-8" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>spitter</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--<init-param>-->
<!--<param-name>spring</param-name>-->
<!--<param-value>classpath:/spring/demo_produce.xml</param-value>-->
<!--</init-param>-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spitter</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spitter</servlet-name>
<url-pattern>*.service</url-pattern>
</servlet-mapping>
</web-app>
以及本次的Debug
的環(huán)境是Tomcat8.0
和Spring4.0.6
版本迁杨,不同的版本之間應(yīng)該會(huì)有一些出入钻心,所以紀(jì)錄一下版本,想要調(diào)試的源代碼版本是Github
上面的AllDemo
的demo_producer
的612dd1316d4d762c166901698ba1818f1b18bfca
版本铅协。
還得補(bǔ)一張完整堆棧圖捷沸。
看了那么多,小結(jié)一下狐史,DispatcherServlet
繼承了FrameWorkServlet
痒给,這個(gè)類里面其實(shí)幫助初始化了Web上下文,最后才是核心控制器的東西骏全。