無聊在家看源碼,雖然沒看懂多少,但是還是想紀錄一下,埋下一顆種子。
有時候,一些問題,我總是想要追根尋底,一直搞的Web開發,但是卻每次只能在Controller
層去編寫代碼,調試代碼,感覺心里總有些(其實是很)不爽,所以擅自超出自己的能力范圍,去看了看Tomcat
和Servlet
和Spring
的源碼,果然如我所料,的確是非常難,所以,只能記下一些關鍵點,為以后留下點東西。
看了好久,直到最后,才發現這個關鍵點,如下圖所示。
發現沒有,這里是三個包之間的交互點,從這三條堆棧的運行來看,就可以看到這三個關鍵點之間是如何交互的。
那么一個一個函數來看。
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);
}
}
}
這個就是Tomcat的那條堆棧的函數??吹胶芏?code>blog都很空泛的說,Web容器
會加載web.xml
的內容,然后加載里面定義的Servlet
,之后會調用init()
的內容,但是都沒有代碼級別的示例,這讓我著實心癢。所以想盡辦法來窺的一絲一毫。
這里函數里面其實已經加載好了Servlet
,如果在Idea
里面把鼠標移動到Servlet
上面可以看到類型就是我在web.xml
里面配置的DispatherServlet
的實例。
關鍵代碼就是Servlet.init(this.facade)
。也就是這里Tomcat
調用Servlet
的init()
函數。這邊也應該要注意到的是參數this.facade
,沒錯,這個就是Servlet
接口中的init(ServletConfig config)
的config
參數,里面最重要的就是給了Servlet
一個ServletContext
的引用,這樣每個Servlet
就可以訪問到唯一的一個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
賦值行為。之后又接著調用了沒有參數的init()
函數。之后就是Spring
的有個HttpServletBean
的類進行了init()
函數的實現。具體源代碼如下。
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");
}
}
從這個函數開始就沒有Tomcat
的什么事情了,就開始進入到Spring
的管理中來了。
好的,下面雖然看的不是很懂了,但是能走幾步就走幾步。
按照調用棧的過程,可以看到之后是FrameworkServlet
的initServletBean
的調用。這回先上代碼。
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
容器,好,在進入這個初始的代碼看看,又做了一些什么事情呢。
protected WebApplicationContext initWebApplicationContext() {
//先嘗試從ServletContext中獲得全局的Spring容器
//全局的Spring容器是通過監聽器獲得的,但是我這里沒有配置
//所以返回的是個null,rootContext=null
WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
WebApplicationContext wac = null;
//分為兩種情況,一種是Bean容器已存在(什么情況下會這樣呢?)
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);
}
//最后調用這個配置和刷新Bean容器
//如果是下面一個創建的分支的話,最后也是會執行這個函數的
this.configureAndRefreshWebApplicationContext(attrName);
}
}
}
//如果沒有初始化,第一次進來的時候一定是沒有初始化的
//找一下?怎么找?
if(wac == null) {
wac = this.findWebApplicationContext();
}
//找不到就造一個,實例化一個
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
這里。有個關鍵一個是把從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());
//將從監聽器獲得的Spring容器作為父容器
wac.setParent(parent);
wac.setConfigLocation(this.getContextConfigLocation());
//調用這個配置和刷新Web應用上下文的函數
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之類的設置進入Web應用上下,下面是refresh()
wac.refresh();
}
再進入到refresh()
函數中,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;
}
}
}
中間跳過無數看不懂的東西,好像是一些事件傳遞,監聽,委托之類的,最后終于調用了DispatherServlet
的onRefresh
函數和initStrategies
函數。但是其實在DispatherServlet
被Tomcat
初始化的時候會先調用DiapatherServlet
的靜態區塊,之后才是無參構造函數。
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);
}
再補上我這個Debug
項目的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
的環境是Tomcat8.0
和Spring4.0.6
版本,不同的版本之間應該會有一些出入,所以紀錄一下版本,想要調試的源代碼版本是Github
上面的AllDemo
的demo_producer
的612dd1316d4d762c166901698ba1818f1b18bfca
版本。
還得補一張完整堆棧圖。
看了那么多,小結一下,DispatcherServlet
繼承了FrameWorkServlet
,這個類里面其實幫助初始化了Web上下文,最后才是核心控制器的東西。