1 SpringMVC 配置XML的方式启动
1.1 XML文件配置
在servlet3.0之前我们可以通过web.xml 配置servlet和监听器
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>
1.2 启动过程分析
Tomcat启动会去扫描web.xml,然后会把监听器和servlet 加入到Tomcat的ServletContext里,首先我们看下ContextLoaderListener。ContextLoaderListener实现了Tomcat的**ServletContextListener **的接口,当Tomcat启动时会调用
contextInitialized()
方法。
我们接下来看下ContextLoaderListener的
contextInitialized()
方法:
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
// 这里有两个重要方法分别为createWebApplicationContext(servletContext)
// 和configureAndRefreshWebApplicationContext(cwac, 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!");
}
servletContext.log("Initializing Spring root WebApplicationContext");
Log logger = LogFactory.getLog(ContextLoader.class);
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) {
//创建WebApplicationContext对象返回的是XmlWebApplicationContext
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);
}
//这里是spring容器的初始化,也是spring容器的启动的位置
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.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException | Error ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
}
我们首先看下
**createWebApplicationContext**
,这里返回的默认是XmlWebApplicationContext。
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
// 根据ServletContext返回对应的 WebApplicationContext 默认为XmlWebApplicationContext
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);
}
接下来我们看下
**configureAndRefreshWebApplicationContext**
方法:
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()));
}
}
// 把ServletContext 放到spring容器中
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);
//这块是不是很熟悉,spring启动的时候就会去调refresh()方法、
//XmlWebApplicationContext继承了AbstractApplicationContext
//所以会去调用AbstractApplicationContext的refresh()方法.
wac.refresh();
}
至此XML方式启动就把Spring容器启动了。这里启动的是spring的根容器。我们先不看DispatcherServlet 类。因为DispatcherServlet 里也启动一个spring web容器,它是根容器的子容器。
1.3 DispatcherServlet
DispatcherServlet 是如何起作用的呢?Tomcat启动的时候会去加载web.xml.读取XML的过程中就会把DispatcherServlet 添加到Tomcat容器中。所以当请求过来的时候就会调用DispatcherServlet 。再接下来其他方式启动的时候我们会分析如何把DispatcherServlet 加入到Tomcat容器里。
2 SpringMVC纯注解模式启动
2.1 Servlet3.0的注解开发
Servlet3.0之后我们发现就可以用纯注解的模式去配置servlet。可以参考servlet3.0官方文档:直接通过在类上注解**@WebServlet**,@WebListener,@WebFilter等注解实现Servlet 、Listener、以及Filter。
Servlet3.0还提供了新的特新,如果说 3.0 版本新增的注解支持是为了简化 Servlet/ 过滤器 / 监听器的声明,从而使得 web.xml 变为可选配置, 那么新增的可插性 (pluggability) 支持则将 Servlet 配置的灵活性提升到了新的高度。熟悉 Struts2 的开发者都知道,Struts2 通过插件的形式提供了对包括 Spring 在内的各种开发框架的支持,开发者甚至可以自己为 Struts2 开发插件,而 Servlet 的可插性支持正是基于这样的理念而产生的。使用该特性,现在我们可以在不修改已有 Web 应用的前提下,只需将按照一定格式打成的 JAR 包放到 WEB-INF/lib 目录下,即可实现新功能的扩充,不需要额外的配置。
首先我们自己开发一个:
在META-INF/services目录中的创建一个名称为javax.servlet.ServletContainerInitializer文件,内容是对应实现tomcat的ServletContainerInitializer类的自定义 MyServletContainerInitializer全类名
//@HandlesTypes(WebService.class) 是tomcat 的注解,会加载实现WebService类的所有子类以及抽象类
@HandlesTypes(WebService.class)
public class MyServletContainerInitializer implements ServletContainerInitializer {
// Set<Class<?>> c 就是@HandlesTypes 加载的类
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
// 在此,使用JAX-WS 特定的代码来初始化运行库和设置mapping等。
ServletRegistration reg = ctx.addServlet("JAXWSServlet", "com.sun.webservice.JAXWSServlet");
//对应的拦截地址
reg.addServletMapping("/foo");
}
}
Tomcat容器启动的时候就会调用MyServletContainerInitializer 的
** onStartup() **
方法。就会把JAXWSServlet加入到tomcat 容器中。
2.2 SpringMVC 是如何实现可插性配置的
结合Servlet3.0的新特性,我们去springweb的jar去寻找对应的javax.servlet.ServletContainerInitializer文件。我们可以发现Spring实现的ServletContainerInitializer。
我们进去看下SpringServletContainerInitializer类:
// 会去实现查找实现WebApplicationInitializer的所有的类包括抽象类
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
throws ServletException {
List<WebApplicationInitializer> initializers = new LinkedList<>();
if (webAppInitializerClasses != null) {
for (Class<?> waiClass : webAppInitializerClasses) {
// Be defensive: Some servlet containers provide us with invalid classes,
// no matter what @HandlesTypes says...
// 判断不是接口类或者不是抽象类然后初始化
if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
try {
initializers.add((WebApplicationInitializer)
ReflectionUtils.accessibleConstructor(waiClass).newInstance());
}
catch (Throwable ex) {
throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
}
}
}
}
if (initializers.isEmpty()) {
servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
return;
}
servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
//调用子类的方法
initializer.onStartup(servletContext);
}
}
}
那我们接下来就去看下**WebApplicationInitializer **这个类,这是个接口类,所以我们要看他的实现类。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5Z1qhi1l-1612848221233)(https://tcs.teambition.net/storage/312286ff59e0a6a28ba068e261f32e20d125?Signature=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBcHBJRCI6IjU5Mzc3MGZmODM5NjMyMDAyZTAzNThmMSIsIl9hcHBJZCI6IjU5Mzc3MGZmODM5NjMyMDAyZTAzNThmMSIsIl9vcmdhbml6YXRpb25JZCI6IiIsImV4cCI6MTYxMzQ0OTEyNSwiaWF0IjoxNjEyODQ0MzI1LCJyZXNvdXJjZSI6Ii9zdG9yYWdlLzMxMjI4NmZmNTllMGE2YTI4YmEwNjhlMjYxZjMyZTIwZDEyNSJ9.aTlmx9lh0-vM6xDf2NalpUIHpgd-Xi2lBCAwxEDisoc&download=image.png “”)]
我们点击去看到他没有实现类。那这改怎么办?我们参考下SpringMVC的官方文档看下。springMVC给的文档是让我们实现
**WebApplicationInitializer **
开不开心?
import org.springframework.web.WebApplicationInitializer;
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
// 我们手动把DispatcherServlet加入到Tomcat容器中了。
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
或者实现**AbstractAnnotationConfigDispatcherServletInitializer **
// 扫描基于注解的类加载
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
// 扫描根容器的配置类
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
// 扫描spring web 容器的 配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { MyWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
这两个配置类的作用是什么呢? 就是 为了拆分 spring 加载类,以便于互不影响,根容器扫描getRootConfigClasses ,子容器扫描getServletConfigClasses 。spring的 dao 、service 层的加载不需要spring web容器控制。这样如果我们把spring web MVC 直接 替换成structs 也不会影响到后端业务。我们在接下来的代码分析中可以看到调用这两个的地方。
再或者**AbstractDispatcherServletInitializer **
// 基于XML配置的
public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
@Override
protected WebApplicationContext createServletApplicationContext() {
XmlWebApplicationContext cxt = new XmlWebApplicationContext();
cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
return cxt;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
2.3 启动流程分析
我们分析下继承**AbstractAnnotationConfigDispatcherServletInitializer **类的启动流程吧。
首先看下整体UML结构图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9RLI1SPc-1612848221237)(https://tcs.teambition.net/storage/3122d37dee3f7c58e38afffb460f00585afa?Signature=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBcHBJRCI6IjU5Mzc3MGZmODM5NjMyMDAyZTAzNThmMSIsIl9hcHBJZCI6IjU5Mzc3MGZmODM5NjMyMDAyZTAzNThmMSIsIl9vcmdhbml6YXRpb25JZCI6IiIsImV4cCI6MTYxMzQ0OTEyNSwiaWF0IjoxNjEyODQ0MzI1LCJyZXNvdXJjZSI6Ii9zdG9yYWdlLzMxMjJkMzdkZWUzZjdjNThlMzhhZmZmYjQ2MGYwMDU4NWFmYSJ9.l-Ip0L4rcTj38Wvihp9EJaXI88qMN2G_EFU838lKygM&download=image.png “”)]
1、首先tomcat启动会去执行SpringServletContainerInitializer 调用onStartup方法。而onStartup方法里又会去执行WebApplicationInitializer子类的onStartup方法 。子类没有会去调用父类AbstractDispatcherServletInitializer的onStartup方法:
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//调用父类的onStartup
super.onStartup(servletContext);
//注册servlet,把DispatcherServlet添加到Tomcat中
registerDispatcherServlet(servletContext);
}
调用父类AbstractContextLoaderInitializer 的onStartup。
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerContextLoaderListener(servletContext);
}
protected void registerContextLoaderListener(ServletContext servletContext) {
// createRootApplicationContext,根容器,也就是spring容器。调用 子类的方法
WebApplicationContext rootAppContext = createRootApplicationContext();
if (rootAppContext != null) {
// 这块ContextLoaderListener 熟悉不?和XML中配置的是一样的,增加监听器,servlet启动的时候回去启动spring容器
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");
}
}
继续看子类的createRootApplicationContext方法
@Override
@Nullable
protected WebApplicationContext createRootApplicationContext() {
//获取扫描类添加到spring web容器中
Class<?>[] configClasses = getRootConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
// 初始化AnnotationConfigWebApplicationContext
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(configClasses);
return context;
}
else {
return null;
}
}
看了半天也没看到spring调用refresh()方法。这个是什么时候调用的呢?
看下这段代码是不是很熟悉。
ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
和XML中配置的是一样的,增加监听器,servlet启动的时候会去启动spring根容器。
接着我们走下断点,然后我们发现其实在tomcat实例化servlet的时候就回去调用servlet的init方法。我们可以看到到DispatcherServlet是实现tomcat的servlet的。还发现了DispatcherServlet里也创建了一个WebApplicationContext。这个容器是干啥的呢?既然都已经启动了一个spring根容器,为什么又创建了一个容器呢?
servlet启动时会调用servlet实现类的init方法,最终调用init方法会调用initServletBean()方法,主要看initWebApplicationContext() 方法
@Override
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");
if (logger.isInfoEnabled()) {
logger.info("Initializing Servlet '" + getServletName() + "'");
}
long startTime = System.currentTimeMillis();
try {
//初始化容器
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException | RuntimeException ex) {
logger.error("Context initialization failed", ex);
throw ex;
}
if (logger.isDebugEnabled()) {
String value = this.enableLoggingRequestDetails ?
"shown which may lead to unsafe logging of potentially sensitive data" :
"masked to prevent unsafe logging of potentially sensitive data";
logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
"': request parameters and headers will be " + value);
}
if (logger.isInfoEnabled()) {
logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
}
}
protected WebApplicationContext initWebApplicationContext() {
// 获取根容器,此时根容器已经启动了。
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
// 判断是否为空,此时是不为空的,添加DispatcherServlete的时候我们会分析
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
// 设置父子容器的关系
cwac.setParent(rootContext);
}
// springweb容器的初始化
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
// 创建spring web的子容器
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;
}
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
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
if (this.contextId != null) {
wac.setId(this.contextId);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
}
}
wac.setServletContext(getServletContext());
wac.setServletConfig(getServletConfig());
wac.setNamespace(getNamespace());
wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
// 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(getServletContext(), getServletConfig());
}
postProcessWebApplicationContext(wac);
applyInitializers(wac);
wac.refresh();
}
至此springmvc纯注解模式的初始化流程算是分析完毕了。
我们接下来看下DispatcherServlet 是如何添加到tomcat 的容器中的。在上边的onStartup方法中我们看registerDispatcherServlet
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//调用父类的onStartup
super.onStartup(servletContext);
//注册servlet,把DispatcherServlet添加到Tomcat中
registerDispatcherServlet(servletContext);
}
protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return empty or null");
// 创建 spring web 子容器
WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.notNull(servletAppContext,
"createServletApplicationContext() did not return an application " +
"context for servlet [" + servletName + "]");
FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());
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.");
// 将DispatcherServlet增加到Tomcat容器中
registration.setLoadOnStartup(1);
registration.addMapping(getServletMappings());
registration.setAsyncSupported(isAsyncSupported());
Filter[] filters = getServletFilters();
if (!ObjectUtils.isEmpty(filters)) {
for (Filter filter : filters) {
registerServletFilter(servletContext, filter);
}
}
customizeRegistration(registration);
}
//创建spring web 子容器
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
// 这就是上边 说的扫描 spring web 子容器 需要加载类的调用我们自定义的MyWebAppInitializer 的方法。
Class<?>[] configClasses = getServletConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
servletAppContext.register(configClasses);
}
return servletAppContext;
rvletApplicationContext() {
AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
// 这就是上边 说的扫描 spring web 子容器 需要加载类的调用我们自定义的MyWebAppInitializer 的方法。
Class<?>[] configClasses = getServletConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
servletAppContext.register(configClasses);
}
return servletAppContext;
}