spring mvc源码学习笔记之十

前面的文章介绍了用 WebApplicationInitializer 或者 AbstractAnnotationConfigDispatcherServletInitializer 来代替 web.xml

我们学 java web 的时候就知道,servlet 容器会自动加载 web.xml

那么,疑问就来了,WebApplicationInitializer 或者 AbstractAnnotationConfigDispatcherServletInitializer 既然替代了 web.xml,那应该也会被 servlet 容器加载,是不是这样呢?答案是:是的。

而完成这个加载工作的是 SpringServletContainerInitializer 类。看下它的源码:

java 复制代码
package org.springframework.web;  
  
import java.lang.reflect.Modifier;  
import java.util.LinkedList;  
import java.util.List;  
import java.util.ServiceLoader;  
import java.util.Set;  
import javax.servlet.ServletContainerInitializer;  
import javax.servlet.ServletContext;  
import javax.servlet.ServletException;  
import javax.servlet.annotation.HandlesTypes;  
  
import org.springframework.core.annotation.AnnotationAwareOrderComparator;  
import org.springframework.lang.Nullable;  
import org.springframework.util.ReflectionUtils;  
  
/**
* 本类继承了 servlet 3.0 的 ServletContainerInitializer 接口。
* 下面这段话的意思是:
* servlet 3.0 的 ServletContainerInitializer 接口是用来让 servlet 容器支持基于编码的配置。
* 在这个过程中要结合 spring 的 WebApplicationInitializer。
* 而 spring 的 WebApplicationInitializer 可以替换 web.xml 也可以结合 web.xml 一起使用。
*
* Servlet 3.0 {@link ServletContainerInitializer} designed to support code-based  
* configuration of the servlet container using Spring's {@link WebApplicationInitializer}  
* SPI as opposed to (or possibly in combination with) the traditional  
* {@code web.xml}-based approach.  
*
* 当 servlet 容器启动的时候,如果累路径下有 spring-web 的话,这个类会被加载,并且 onStartup 方法会被调用。
* 这背后的原理在于 java 的 SPI 机制。
* spring-web 模块下有个 META-INF/services/javax.servlet.ServletContainerInitializer 文件,
* 其内容就是当前类的完全限定名。
*
* <h2>Mechanism of Operation</h2>  
* This class will be loaded and instantiated and have its {@link #onStartup}  
* method invoked by any Servlet 3.0-compliant container during container startup assuming  
* that the {@code spring-web} module JAR is present on the classpath. This occurs through  
* the JAR Services API {@link ServiceLoader#load(Class)} method detecting the  
* {@code spring-web} module's {@code META-INF/services/javax.servlet.ServletContainerInitializer}  
* service provider configuration file. See the  
* <a href="http://download.oracle.com/javase/6/docs/technotes/guides/jar/jar.html#Service%20Provider">  
* JAR Services API documentation</a> as well as section <em>8.2.4</em> of the Servlet 3.0  
* Final Draft specification for complete details.  
*  
* <h3>In combination with {@code web.xml}</h3>  
* A web application can choose to limit the amount of classpath scanning the Servlet  
* container does at startup either through the {@code metadata-complete} attribute in  
* {@code web.xml}, which controls scanning for Servlet annotations or through an  
* {@code <absolute-ordering>} element also in {@code web.xml}, which controls which  
* web fragments (i.e. jars) are allowed to perform a {@code ServletContainerInitializer}  
* scan. When using this feature, the {@link SpringServletContainerInitializer}  
* can be enabled by adding "spring_web" to the list of named web fragments in  
* {@code web.xml} as follows:  
*  
* <pre class="code">  
* {@code  
* <absolute-ordering>  
* <name>some_web_fragment</name>  
* <name>spring_web</name>  
* </absolute-ordering>  
* }</pre>  
*
* SpringServletContainerInitializer 可以看做一个简单的代理,真正的工作还是交给了 WebApplicationInitializer 。
*
* <h2>Relationship to Spring's {@code WebApplicationInitializer}</h2>  
* Spring's {@code WebApplicationInitializer} SPI consists of just one method:  
* {@link WebApplicationInitializer#onStartup(ServletContext)}. The signature is intentionally  
* quite similar to {@link ServletContainerInitializer#onStartup(Set, ServletContext)}:  
* simply put, {@code SpringServletContainerInitializer} is responsible for instantiating  
* and delegating the {@code ServletContext} to any user-defined  
* {@code WebApplicationInitializer} implementations. It is then the responsibility of  
* each {@code WebApplicationInitializer} to do the actual work of initializing the  
* {@code ServletContext}. The exact process of delegation is described in detail in the  
* {@link #onStartup onStartup} documentation below.  
*  
* <h2>General Notes</h2>  
* In general, this class should be viewed as <em>supporting infrastructure</em> for  
* the more important and user-facing {@code WebApplicationInitializer} SPI. Taking  
* advantage of this container initializer is also completely <em>optional</em>: while  
* it is true that this initializer will be loaded and invoked under all Servlet 3.0+  
* runtimes, it remains the user's choice whether to make any  
* {@code WebApplicationInitializer} implementations available on the classpath. If no  
* {@code WebApplicationInitializer} types are detected, this container initializer will  
* have no effect.  
*  
* <p>Note that use of this container initializer and of {@code WebApplicationInitializer}  
* is not in any way "tied" to Spring MVC other than the fact that the types are shipped  
* in the {@code spring-web} module JAR. Rather, they can be considered general-purpose  
* in their ability to facilitate convenient code-based configuration of the  
* {@code ServletContext}. In other words, any servlet, listener, or filter may be  
* registered within a {@code WebApplicationInitializer}, not just Spring MVC-specific  
* components.  
*
* 注意:不要扩展这个类,也不要继承这个类。
* 这个类应该被视为内部类型,不对外。
* 对外的是 WebApplicationInitializer。
*
* <p>This class is neither designed for extension nor intended to be extended.  
* It should be considered an internal type, with {@code WebApplicationInitializer}  
* being the public-facing SPI.  
*  
* <h2>See Also</h2>  
* See {@link WebApplicationInitializer} Javadoc for examples and detailed usage  
* recommendations.<p>  
*  
* @author Chris Beams  
* @author Juergen Hoeller  
* @author Rossen Stoyanchev  
* @since 3.1  
* @see #onStartup(Set, ServletContext)  
* @see WebApplicationInitializer  
*/  
@HandlesTypes(WebApplicationInitializer.class)  
public class SpringServletContainerInitializer implements ServletContainerInitializer {  
  
{  
    System.out.println("@HandlesTypes(WebApplicationInitializer.class) 这个注解表明了当前类 SpringServletContainerInitializer "
                   + " 需要处理的类型是 WebApplicationInitializer ");  
}  
  
/**  
* Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}  
* implementations present on the application classpath.
* 
* <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},  
* Servlet 3.0+ containers will automatically scan the classpath for implementations  
* of Spring's {@code WebApplicationInitializer} interface and provide the set of all  
* such types to the {@code webAppInitializerClasses} parameter of this method.  
* <p>If no {@code WebApplicationInitializer} implementations are found on the classpath,  
* this method is effectively a no-op. An INFO-level log message will be issued notifying  
* the user that the {@code ServletContainerInitializer} has indeed been invoked but that  
* no {@code WebApplicationInitializer} implementations were found.  
* <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,  
* they will be instantiated (and <em>sorted</em> if the @{@link  
* org.springframework.core.annotation.Order @Order} annotation is present or  
* the {@link org.springframework.core.Ordered Ordered} interface has been  
* implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}  
* method will be invoked on each instance, delegating the {@code ServletContext} such  
* that each instance may register and configure servlets such as Spring's  
* {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},  
* or any other Servlet API componentry such as filters.  
* @param webAppInitializerClasses all implementations of  
* {@link WebApplicationInitializer} found on the application classpath  
* @param servletContext the servlet context to be initialized  
* @see WebApplicationInitializer#onStartup(ServletContext)  
* @see AnnotationAwareOrderComparator  
*/  
@Override  
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)  
throws ServletException {  
  
servletContext.log("SpringServletContainerInitializer 利用了 java 的 SPI 机制");  
  
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);  
}  
}  
}  
}  
  
System.out.println("SpringServletContainerInitializer 在其 onStartup 方法中检测类路径下的 WebApplicationInitializer(spring的) ");  
  
if (initializers.isEmpty()) {  
servletContext.log("在类路径下没有检测到 spring 的 WebApplicationInitializer。------- No Spring WebApplicationInitializer types detected on classpath");  
return;  
}  
  
System.out.println("在类路径下检测到了 " + initializers.size() + " 个 spring 的 WebApplicationInitializer。");  
  
servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");  
  
  
AnnotationAwareOrderComparator.sort(initializers);  
  
System.out.println("依次调用 WebApplicationInitializer 的 onStartup 方法");  
  
for (WebApplicationInitializer initializer : initializers) {  
  
System.out.println("调用 " + initializer.getClass().getName() + " 的 onStartup 方法");  
  
initializer.onStartup(servletContext);  
}  
  
System.out.println("至此,通过 servlet、java spi 成功引导了 spring ");  
  
}  
  
}

关于这个类有几个需要注意的点:

  • 它实现了 servlet 3.0 的 javax.servlet.ServletContainerInitializer 接口
  • 它加了个 @HandlesTypes(WebApplicationInitializer.class) 注解
  • 它实现了 javax.servlet.ServletContainerInitializer 接口中定义的 onStartup 方法

总结下来。SpringServletContainerInitializer 这个类实现了 servlet 3.0 的 javax.servlet.ServletContainerInitializer 接口,这就决定了在 servlet 容器启动的时候 onStartUp 方法会被自动触发,而在 onStartUp 方法内部 WebApplicationInitializeronStartUp 方法被调用。这就是 WebApplicationInitializer 被容器带起来的过程。

这里只是说了个大概,要想非常清楚,还请自己研究下 servlet 3.0 的 javax.servlet.ServletContainerInitializer 接口。

相关推荐
9命怪猫2 小时前
AI大模型-提示工程学习笔记5-零提示
人工智能·笔记·学习·ai·提示工程
生如夏花℡4 小时前
JAVA学习记录3
java·学习·idea
shaxin观yin4 小时前
python反序列化+沙箱逃逸++js+redis
python·学习·https
高 朗4 小时前
【GO基础学习】项目日志zap Logger使用
服务器·学习·golang·日志·zap
栗豆包4 小时前
w148基于spring boot的文档管理系统的设计与实现
java·spring boot·后端·spring·tornado
LLLuckyGirl~7 小时前
计算机网络学习
网络·学习·计算机网络
紫云_Zyun7 小时前
JAVA开发学习Day8
java·开发语言·学习·vue
Spcarrydoinb7 小时前
python学习笔记—14—函数
笔记·python·学习
PyAIGCMaster7 小时前
docker学习记录:创建python环境,使用vscode连接远程docker环境,使其访问同为docker镜像的mongodb的设置。
学习·docker·容器
私人珍藏库7 小时前
《繁星路》V1.8.3(Build16632266)官方中文学习版
学习