由上節(jié)二十三、spring mvc之簡單使用,SpringServletContainerInitializer找到所有的WebApplicationInitializer后,會調(diào)用它們的onStartup方法,這節(jié)我們看下AbstractAnnotationConfigDispatcherServletInitializer的onStartup執(zhí)行邏輯胁出。
AbstractAnnotationConfigDispatcherServletInitializer類圖如下:
onStartup方法在AbstractAnnotationConfigDispatcherServletInitializer父類AbstractDispatcherServletInitializer實(shí)現(xiàn):
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
registerDispatcherServlet(servletContext);
}
AbstractDispatcherServletInitializer又調(diào)用它的父類AbstractContextLoaderInitializer的onStartup方法。
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerContextLoaderListener(servletContext);
}
兩個onStartup方法分別調(diào)用了registerDispatcherServlet和registerContextLoaderListener方法段审,從方法名上我們能夠猜出他們的功能全蝶,分別是注冊DispatcherServlet和ContextLoaderListener。接下來我們具體分析這兩個方法寺枉。
registerContextLoaderListener方法
protected void registerContextLoaderListener(ServletContext servletContext) {
//1. 創(chuàng)建Spring上下文
WebApplicationContext rootAppContext = createRootApplicationContext();
if (rootAppContext != null) {
//2. 創(chuàng)建ContextLoaderListener監(jiān)聽器
ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
listener.setContextInitializers(getRootApplicationContextInitializers());
servletContext.addListener(listener);
}
else {
logger.debug("No ContextLoaderListener registered, as " +
"createRootApplicationContext() did not return an application context");
}
}
registerContextLoaderListener方法執(zhí)行邏輯如下:
- 創(chuàng)建Spring上下文抑淫,上下文的創(chuàng)建交給子類AbstractAnnotationConfigDispatcherServletInitializer實(shí)現(xiàn)。
@Override
protected WebApplicationContext createRootApplicationContext() {
//1. 得到配置類路徑姥闪,這個方法給使用者重寫的
Class<?>[] configClasses = getRootConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
//2. 創(chuàng)建AnnotationConfigWebApplicationContext對象
AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
rootAppContext.register(configClasses);
return rootAppContext;
}
else {
return null;
}
}
- 創(chuàng)建ContextLoaderListener監(jiān)聽器,并把監(jiān)聽器添加的servlet上下文中始苇。
初始化Spring上下文
ContextLoaderListener實(shí)現(xiàn)ServletContextListener,在servlet容器啟動的時候就會調(diào)用它的contextInitialized方法筐喳。我們看下它的實(shí)現(xiàn)催式。
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
@Override
public void contextDestroyed(ServletContextEvent event) {
closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
ContextLoaderListener的contextInitialized又調(diào)用父類ContextLoader的initWebApplicationContext方法。
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//1. spring上下文是否已經(jīng)加載過
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) {
this.context = createWebApplicationContext(servletContext);
}
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
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);
}
//2. 調(diào)用refresh加載Spring上下文
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
//3. 設(shè)置spring上下文已經(jīng)加載完成
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方法代碼很長避归,業(yè)務(wù)邏輯不難荣月,主要是做各種判斷。邏輯如下:
- 判斷Spring上下文是否已經(jīng)加載過梳毙,保證只加載一次哺窄。
- 加載Spring上下文,調(diào)用的configureAndRefreshWebApplicationContext账锹,調(diào)用的是我們很熟悉的refresh方法萌业。
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
//刷新
wac.refresh();
}
- 設(shè)置spring上下文已經(jīng)加載完成
registerDispatcherServlet
protected void registerDispatcherServlet(ServletContext servletContext) {
//1. 得到servlet名字,默認(rèn)是dispatcher
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return empty or null");
//2. 創(chuàng)建Servlet上下文
WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.notNull(servletAppContext,
"createServletApplicationContext() did not return an application " +
"context for servlet [" + servletName + "]");
//3. 創(chuàng)建dispatcherServlet
FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());
//4. 注冊dispatcherServlet
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
Assert.notNull(registration,
"Failed to register servlet with name '" + servletName + "'." +
"Check if there is another servlet registered under the same name.");
registration.setLoadOnStartup(1);
registration.addMapping(getServletMappings());
registration.setAsyncSupported(isAsyncSupported());
//5. 注冊過濾器奸柬,這些過濾器都是針對dispatcherServlet咽白,所以不需要配置Mapping
Filter[] filters = getServletFilters();
if (!ObjectUtils.isEmpty(filters)) {
for (Filter filter : filters) {
registerServletFilter(servletContext, filter);
}
}
customizeRegistration(registration);
}
registerDispatcherServlet方法的邏輯也很簡單,命名好的重要性。
- 得到servlet名字鸟缕,默認(rèn)是dispatcher
- 創(chuàng)建Servlet上下文,還是交給子類AbstractAnnotationConfigDispatcherServletInitializer完成.
@Override
protected WebApplicationContext createServletApplicationContext() {
//和Spring上下問使用的是同一種上下文
AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
//子類重寫
Class<?>[] configClasses = getServletConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
servletAppContext.register(configClasses);
}
return servletAppContext;
}
- 創(chuàng)建dispatcherServlet
- 注冊dispatcherServlet
- 注冊過濾器,獲取過濾器由子類重寫,這些過濾器主要是針對dispatcherServlet排抬,對其他的Servlet不生效懂从。
初始化Servlet上下文
registerDispatcherServlet方法中只是創(chuàng)建了Servlet上下文,并沒有加載上下文蹲蒲。那么加載的動作在哪做的呢番甩?
DispatcherServlet的類圖如下:
DispatcherServlet實(shí)現(xiàn)自HttpServlet,在Servlet容器加載的時候届搁,會調(diào)用Servlet的init方法缘薛。DispatcherServlet的init方法在父類HttpServletBean中.
@Override
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// Set bean properties from init parameters.
//1. 設(shè)置初始化參數(shù)
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// Let subclasses do whatever initialization they like.
//2. 初始Servlet,由子類實(shí)現(xiàn)
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
init方法做了兩件事:
- 設(shè)置初始化參數(shù)
- 初始Servlet,子類FrameworkServlet實(shí)現(xiàn)了這個方法
@Override
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
if (this.logger.isInfoEnabled()) {
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
}
long startTime = System.currentTimeMillis();
try {
//初始化Servlet上下文
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
catch (RuntimeException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
if (this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
elapsedTime + " ms");
}
}
上面方法這么長的代碼窍育,只做了一件事,初始化Servlet上下文宴胧。
protected WebApplicationContext initWebApplicationContext() {
//1. 得到Spring上下文
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
//2. 設(shè)置Spring上下文作為當(dāng)前父上下文
cwac.setParent(rootContext);
}
//調(diào)用refresh()
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
初始化Servlet上下文流程如下:
- 得到Spring上下文漱抓,把Spring上下文設(shè)置成Servlet上下文的parent。
- 調(diào)用refresh方法加載上下文恕齐。這里和Spring上下文的邏輯差不多乞娄,就不貼代碼了。
疑惑
為什么Servlet上下文能夠獲得到Spring上下文中的bean显歧。我在DefaultListableBeanFactory的getBean中找到答案:
@Override
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
//1. 從自己的容器中獲取bean
NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args);
if (namedBean != null) {
return namedBean.getBeanInstance();
}
//2. 如果自己容器中沒有仪或,則嘗試從父類容器中獲取
BeanFactory parent = getParentBeanFactory();
if (parent != null) {
return parent.getBean(requiredType, args);
}
throw new NoSuchBeanDefinitionException(requiredType);
}