Servlet 3.0 集成 Spring MVC
简单demo:
github
配置类TestRootConfig
// 扫描包下除了controller的bean
@ComponentScan(value = "com.tianwen.spring", excludeFilters = {@ComponentScan.Filter(classes = {Controller.class})})
@EnableWebMvc
public class TestRootConfig {
}
配置类TestServletConfig
// 只扫描包下的controller
@ComponentScan(value = "com.tianwen.spring", includeFilters = {@ComponentScan.Filter(classes = {Controller.class})})
@Configuration
public class TestServletConfig {
}
MyController
@RestController
@RequestMapping(value = "/controller")
public class MyController {
@Autowired
private MyService myService;
@GetMapping(value = "/method1")
public MyResult method1() {
return myService.method1();
}
}
MyService
@Service
public class MyService {
public MyResult method1() {
return new MyResult(1, "wang");
}
}
MyResult
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MyResult {
private Integer id;
private String name;
}
最重要的TestWebAppInitializer
public class TestWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{TestRootConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{TestServletConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
请求接口结果:{"id":1,"name":"wang"}
分析:
根据Servlet3.0规范8.2.4章节,大体翻译过来的意思是:Servlet容器启动时,会尝试扫描以寻找ServletContainerInitializer
接口的实现类。而框架提供的实现ServletContainerInitializer
接口的实现类,必须在META-INF/services
目录下名为javax.servlet.ServletContainerInitializer
的文件内声明,并且实现类上通常会标注HandlesTypes
注解,以声明实现类感兴趣的类。这样,Servlet容器启动时,实现类的onStartup
方法会被调用,感兴趣的类会被传入到实现类的onStartup
方法中。注意:Servlet3.0规范被Tomcat7.x及以后的版本所支持。
参考 Servlet 3.0 Specification
分析demo工程,在spring-web
这个jar下,很容易找到javax.servlet.ServletContainerInitializer
文件,如图所示。
可以看到文件内声明的实现
ServletContainerInitializer
接口的实现类为org.springframework.web.SpringServletContainerInitializer
。
SpringServletContainerInitializer
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
throws ServletException {
List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();
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) 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);
}
}
}
-
WebApplicationInitializerHandlesTypes
注解上的value
为WebApplicationInitializer.class
onStartup
方法中传入两个参数,一个为WebApplicationInitializer
的子类及实现类,另一个为Servlet容器上下文servletContext
-
TestWebAppInitializer关系图onStartup
方法内,将非接口、非抽象类且继承WebApplicationInitializer
的类,利用反射实例化,加入到集合中。在demo工程中,这里能收集到集合中的类,只有自定义的TestWebAppInitializer
-
调用收集到的类的
onStartup
方法,传入servletContext
。TestWebAppInitializer
的onStartup
方法会被调用,该方法继承自基类AbstractDispatcherServletInitializer
。 -
AbstractDispatcherServletInitializer
public abstract class AbstractDispatcherServletInitializer extends AbstractContextLoaderInitializer {
...
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
registerDispatcherServlet(servletContext);
}
...
调用父类的AbstractContextLoaderInitializer
的onStartup
方法
AbstractContextLoaderInitializer
public abstract class AbstractContextLoaderInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerContextLoaderListener(servletContext);
}
protected void registerContextLoaderListener(ServletContext servletContext) {
WebApplicationContext rootAppContext = createRootApplicationContext();
if (rootAppContext != null) {
...
}
...
-
registerContextLoaderListener
方法内调用的createRootApplicationContext
方法在AbstractAnnotationConfigDispatcherServletInitializer
中
AbstractAnnotationConfigDispatcherServletInitializer
public abstract class AbstractAnnotationConfigDispatcherServletInitializer
extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createRootApplicationContext() {
Class<?>[] configClasses = getRootConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
rootAppContext.register(configClasses);
return rootAppContext;
}
else {
return null;
}
}
...
其中getRootConfigClasses
方法来自自定义类TestWebAppInitializer
,返回了定义好的配置类TestRootConfig
。创建spring根ioc容器AnnotationConfigWebApplicationContext
。
- 回到
AbstractContextLoaderInitializer
的registerContextLoaderListener
方法
public abstract class AbstractContextLoaderInitializer implements WebApplicationInitializer {
protected void registerContextLoaderListener(ServletContext servletContext) {
...
if (rootAppContext != null) {
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");
}
}
...
拿到根容器之后,创建监听器ContextLoaderListener
,然后为Servlet容器设置监听器。
- 回到
AbstractDispatcherServletInitializer
的onStartup
方法中,在调用完基类的onStartup
后,接着调用registerDispatcherServlet
方法。
public abstract class AbstractDispatcherServletInitializer extends AbstractContextLoaderInitializer {
protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return empty or null");
WebApplicationContext servletAppContext = createServletApplicationContext();
...
再创建一个ioc容器,在父类AbstractAnnotationConfigDispatcherServletInitializer
中。
AbstractAnnotationConfigDispatcherServletInitializer
public abstract class AbstractAnnotationConfigDispatcherServletInitializer
extends AbstractDispatcherServletInitializer {
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
Class<?>[] configClasses = getServletConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
servletAppContext.register(configClasses);
}
return servletAppContext;
}
创建ioc容器AnnotationConfigWebApplicationContext servletAppContext
,getServletConfigClasses
方法来自自定义类TestWebAppInitializer
,返回了定义好的配置类TestServletConfig
。将配置类设置到容器中。
- 回到
AbstractDispatcherServletInitializer
的registerDispatcherServlet
中
public abstract class AbstractDispatcherServletInitializer extends AbstractContextLoaderInitializer {
protected void registerDispatcherServlet(ServletContext servletContext) {
...
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.");
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);
}
获取到承载Servlet的ioc容器后,创建DispatcherServlet
,向Servlet
容器中注册Servlet
,设置启动顺序,设置需要被DispatcherServlet
处理的mapping
,getServletMappings
方法来自自定义类TestWebAppInitializer
,配置的是/
,以处理所有请求。TestWebAppInitializer
内没有重写getServletFilters
方法,不会取到过滤器。
-
onStartup
方法执行完成后,伴随着tomcat容器的启动,设置的监听器ContextLoaderListener
开始初始化。
ContextLoaderListener
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
ContextLoader
的initWebApplicationContext
方法,主要关注其中的configureAndRefreshWebApplicationContext
方法。
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!");
}
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.
// context为onStartUp过程中创建的根容器
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);
}
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.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;
}
}
...
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();
}
-
AbstractApplicationContext
方法内最终调用了熟悉的AbstractApplicationContext
的refresh
方法完成容器的创建,这是springIoc容器的核心,将在另外篇章记录。
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
总结:
-
spring-web
的jar下,META-INF/services
目录下名为javax.servlet.ServletContainerInitializer
文件内,配置了类SpringServletContainerInitializer
。 - Servlet容器启动时,
SpringServletContainerInitializer
的onStartup
方法会被调用。方法入参一:传入注解HandlesTypes
上配置的WebApplicationInitializer
类的子类及实现类。方法入参二:传入Servlet
容器。 - 接着
AbstractContextLoaderInitializer
的onStartup
方法被调用。创建IOC容器作为根容器rootAppContext
(AnnotationConfigWebApplicationContext
),创建监听器ContextLoaderListener
,并为Servlet容器设置监听器。 - 接着
AbstractDispatcherServletInitializer
的registerDispatcherServlet
方法被调用,创建IOC容器作为承载servlet的容器(注意区分Servlet容器与承载servlet的ioc容器)。创建DispatcherServlet
,将DispatcherServlet
添加到Servlet容器中。 - 随着Servlet容器启动,设置的监听器开始工作,监听器的初始化方法中,拿到声明的根容器,最终执行熟悉refresh方法。