springmvc 注解启动servlet

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

学习记录:tomcat的理解


提示:以下是本篇文章正文内容,下面案例可供参考

一、XML配置Servlet

ContextLoaderListener实现了ServletContextListener这个接口的contextInitialized 方法。这个是启动spring的关键。

DispatcherServlet则是启动springmvc的关键,DispatcherServlet 继承关系如下
HttpServlet<-HttpServletBean<-FrameworkServlet<-DispatcherServlet;

以上两个类是不可缺失的。
早期我们是通过xml配置来加载两个类的。如下:

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-dispatcher.xml</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>

那tomcat 是如何与spring进行整合的,接下来我们看看tomcat的spi机制

二、Tomcat 加载机制:SPI

下面我们自己起的一个示例,看看tomcat是如何实现SPI。

public class SpringApplication {

    public static void main(String[] args) throws LifecycleException, ServletException {
        run(SpringApplication.class, args);
    }


    public static void run(Object source, String... args) {
        try {
            // Tomcat容器
            Tomcat tomcatServer = new Tomcat();
            // 端口号
            tomcatServer.setPort(9090);
            // 读取项目路径 加载静态资源
            StandardContext ctx = (StandardContext) tomcatServer.addWebapp("/", new File("src/main").getAbsolutePath());
            // 禁止重新载入
            ctx.setReloadable(false);
            // class文件读取地址
            File additionWebInfClasses = new File("spring-source/target/classes");
            // 创建WebRoot
            WebResourceRoot resources = new StandardRoot(ctx);
            // tomcat内部读取Class执行
            resources.addPreResources(
                    new DirResourceSet(resources, "/spring-demo/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
            tomcatServer.start();
            // 同步等待请求
            tomcatServer.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}

至此一个tomcat启动完成,接下我们需要把servlet和listener 从配置文件中去除。

  1. Tomcat 启动的时候会自动加载 /resources/META-INF/services/javax.servlet.ServletContainerInitializer 文件,相当于是一个SPI
    springmvc 注解启动servlet
//tomcat 会自动加载所有实现LoadServlet的类放在set容器中。并调用onStartup方法
@HandlesTypes(LoadServlet.class)
public class MyServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        Iterator var4;
        if (set != null) {
            var4 = set.iterator();
            while (var4.hasNext()) {
                Class<?> clazz = (Class<?>) var4.next();
                if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()) && LoadServlet.class.isAssignableFrom(clazz)) {
                    try {
                    	//在这里调用我们自己实现的loadOnstarp的方法
                        ((LoadServlet) clazz.newInstance()).loadOnstarp(servletContext);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

public interface LoadServlet {
    void loadOnstarp(ServletContext servletContext);
}
public class LoadServletImpl implements LoadServlet {
    @Override
    public void loadOnstarp(ServletContext servletContext) {
        ServletRegistration.Dynamic initServlet = servletContext.addServlet("initServlet", "com.test.servlet.InitServlet");
        initServlet.setLoadOnStartup(1);
        initServlet.addMapping("/init");
    }
}

在LoadServletImpl 中我们自己注入Servlert.

三、Spring mvc 加载实现原理

springmvc 注解启动servlet
spring-web 同样有配置文件:META-INF/services/javax.servlet.ServletContainerInitializer,那么tomcat启动的时候会加载SpringServletContainerInitializer,我们来看看这个类究竟做了什么操作。

//tomcat 会自动加载所有实现WebApplicationInitializer的类放在set容器中。并调用onStartup方法
@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接口的类,然后调用onStartUp方法。我们先来看看AbstractContextLoaderInitializer这个类

public abstract class AbstractContextLoaderInitializer implements WebApplicationInitializer {
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		registerContextLoaderListener(servletContext);
	}
protected void registerContextLoaderListener(ServletContext servletContext) {

		//创建spring上下文,注册了SpringContainer
		WebApplicationContext rootAppContext = createRootApplicationContext();
		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");
		}
	}
}

可以看到这个类实际上帮我们注册了监听器,接下来我们再看看AbstractDispatcherServletInitializer

public abstract class AbstractDispatcherServletInitializer extends AbstractContextLoaderInitializer {
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		super.onStartup(servletContext);
		//注册DispatcherServlet
		registerDispatcherServlet(servletContext);
	}
protected void registerDispatcherServlet(ServletContext servletContext) {
		String servletName = getServletName();
		Assert.hasLength(servletName, "getServletName() must not return null or empty");

		//创建springmvc的上下文,注册了MvcContainer类
		WebApplicationContext servletAppContext = createServletApplicationContext();
		Assert.notNull(servletAppContext, "createServletApplicationContext() must not return null");

		//创建DispatcherServlet
		FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
		Assert.notNull(dispatcherServlet, "createDispatcherServlet(WebApplicationContext) must not return null");
		dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());

		ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
		if (registration == null) {
			throw new IllegalStateException("Failed to register servlet with name '" + servletName + "'. " +
					"Check if there is another servlet registered under the same name.");
		}

		/*
		* 如果该元素的值为负数或者没有设置,则容器会当Servlet被请求时再加载。
			如果值为正整数或者0时,表示容器在应用启动时就加载并初始化这个servlet,
			值越小,servlet的优先级越高,就越先被加载
		* */
		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);
	}
}

可以看到这个类实际上帮我们注册了DispatcherServlet。

到此我们已经注册了Listener 和Servelet,接下来我们看下是再哪里加载我们spring 容器。

四、加载spring 容器

tomcat 初始化完成后会调用ContextLoaderListener 中的 contextInitialized。
调用链是:
ContextLoaderListener -> contextInitialized
-> initWebApplicationContext -> configureAndRefreshWebApplicationContext -> onrefresh
最终会调用我们spring 的refresh 方法 ,初始化spring 容器,下面是一些重要过程代码。

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) {
				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容器
					configureAndRefreshWebApplicationContext(cwac, servletContext);
				}
			}
			//把spring容器放在serveletContext中
			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;
		}
	}

这里实际上就是调用spring refresh 方法,初始化spring容器放在ServletContext容器中,以便后面的调用。接下来我们看一下DispatchServlet。众所周知:Servlet实例化后会被tomcat 调用init 的方法,
调用链如下:
init -> initServletBean -> initWebApplicationContext -> configureAndRefreshWebApplicationContext -> refresh()


protected WebApplicationContext initWebApplicationContext() {
		//这里会从servletContext中获取到父容器,就是通过监听器加载的容器
		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
						//父容器如果为空,则将 监听器加载的容器 设置为父容器。
						cwac.setParent(rootContext);
					}
					//容器加载
					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.
			synchronized (this.onRefreshMonitor) {
				onRefresh(wac);
			}
		}

		if (this.publishContext) {
			// Publish the context as a servlet context attribute.
			String attrName = getServletContextAttributeName();
			getServletContext().setAttribute(attrName, wac);
		}

		return wac;
	}

这里需要注意的是,ServletContextListener帮我们实例化了一个IOC容器,DispatcherServlet实际上也实例化了另一个IOC容器,listener的是spring mvc 容器主要管理我们的controller类,servlet是spring 容器主要管理service以及repo类。而他们之间则存在父子关系。spring mvc是子,spring是父,子可以调用父的bean。

总结

本文主要讲解了Spring 如何不通过xml文件来注册Listener 和Servlet,这里主要用了tomcat 的spi机制。第二则是解释了如何将spring 容器装载至ServletContext的过程。
servletContext 及spring、springmvc关系如下
servletContext 拥有spring mvc而spring mvc 拥有spring。

上一篇:Servlet笔记①


下一篇:Servlet详细解析