Spring MVC 源碼解析(二)— 容器初始化

一、什麼是servlet容器

servlet咱們能夠把它理解成是基於java語言的web組件,每個servlet都有本身的生命週期包括init()service()destroy()而這些都是經過servlet container管理的。客戶端經過servlet 容器實現的 request/response paradigm(請求/應答模式)與servlet進行交互。Servlet Container 是 Web 服務器或者應用服務器的一部分,用於提供基於請求/響應發送模式的網絡服務,解碼基於 MIME(全稱是"Multipurpose Internet Mail Extensions",中譯爲"多用途互聯網郵件擴展",指的是一系列的電子郵件技術規範) 的請求,而且格式化基於 MIME 的響應。Servlet 容器能夠嵌入到宿主的 Web 服務器中,或者經過 Web 服務器的本地擴展 API 單獨做爲附加組件安裝。Servelt 容器也可能內嵌或安裝到啓用 Web 功能的應用服務器中。目前 Spring boot 就內嵌了 tomcat、jetty等web容器。java

二、Servlet 容器初始化時 Spring Mvc 都作了什麼

在web.xml的文件中可看到以下配置:web

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 
複製代碼

這個配置的意思是在servlet 容器中增長一個監聽器,當容器初始化的時候會拋出ServletContextEvent事件,監聽器監聽到該事件就會調用 ContextLoaderListener.contextInitialized(ServletContextEvent event)方法來初始化Spring mvc rootContextspring

/**
	 * Initialize the root web application context.
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}
複製代碼

三、Spring Mvc 容器結構

Spring Mvc 的容器是分層的,當咱們的web應用有多個servlet的時候,一些公共的資源(bean)就能夠放在root WebApplicationContext 中 好比dataSourceservice等,在Spring Mvc中 每一servlet 都有對應的屬於本身的一個servlet WebApplicationContext 這些ControllersViewResolver等就能夠放到與之相關連的WebapplicationContext 中:json

當咱們只有一個 servlet 時,固然能夠把因此的 bean 都交由 root WebApplicationContext 來管理,這樣 Spring Mvc 就會經過代理的形式生成一個空的與之對應的容器。

四、java 配置容器

servlet 3.0 之後支持用過java 代碼來配置容器,servlet提供了一個接口:spring-mvc

public interface ServletContainerInitializer {

    /**
     * Receives notification during startup of a web application of the classes
     * within the web application that matched the criteria defined via the
     * {@link javax.servlet.annotation.HandlesTypes} annotation.
     *
     * @param c     The (possibly null) set of classes that met the specified
     *              criteria
     * @param ctx   The ServletContext of the web application in which the
     *              classes were discovered
     *
     * @throws ServletException If an error occurs
     */
    void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException;
}
複製代碼

servlet 容器在啓動的時候回到 classpath 下掃描這個接口的實現。spring Mvc 分裝了一層代理實現了這個接口:tomcat

@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);
		}
	}
複製代碼

在實際使用中只要實現Spring Mvc 爲咱們提供的接口便可;bash

public interface WebApplicationInitializer {

	/**
	 * Configure the given {@link ServletContext} with any servlets, filters, listeners
	 * context-params and attributes necessary for initializing this web application. See
	 * examples {@linkplain WebApplicationInitializer above}.
	 * @param servletContext the {@code ServletContext} to initialize
	 * @throws ServletException if any call against the given {@code ServletContext}
	 * throws a {@code ServletException}
	 */
	void onStartup(ServletContext servletContext) throws ServletException;

}
複製代碼

咱們能夠經過這個接口來完成servlet 容器 以及 Spring Mvc 容器的初始化工做,這樣作就能夠將項目中的配置文件完全消滅掉。服務器

五、如何消滅配置文件

去除 web.xml

<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://java.sun.com/xml/ns/j2ee ">

    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-servlet.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <!-- 若是不想用默認的配置文件名,能夠在這裏指定. 核心文件名規則:xxx-servlet.xml,xxx是<servlet-name>的名字 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc-servlet.xml</param-value>
    </context-param>
    <!-- Spring ContextLoaderListener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Post請求中文亂碼 -->
    <filter>
        <filter-name>CharacterEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
複製代碼

經過java 代碼能夠將其改造爲:網絡

public class DemoServletinitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        //初始化root WebApplicationContext
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(DemoRootApplicationContextConfiguration.class);
        servletContext.addListener(new ContextLoaderListener(rootContext));

        //初始化 servlet WebApplicationContext
        AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
        webApplicationContext.register(DemoWebMvcConfiguration.class);

        //註冊 servlet
        ServletRegistration.Dynamic registration = servletContext.addServlet("demo", new DispatcherServlet(webApplicationContext));
        registration.setLoadOnStartup(1);
        registration.addMapping("/");

        //註冊 filter
        FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", CharacterEncodingFilter.class);
        characterEncoding.setInitParameter("encoding", "UTF-8");
        characterEncoding.setInitParameter("forceEncoding", "true");

    }
}
複製代碼

去除 xxx-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="demo" />


    <mvc:annotation-driven />

    <!-- 啓用註解配置 -->
    <context:annotation-config />

    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
                    <property name="extractValueFromSingleKeyModel" value="true" />
                </bean>
            </list>
        </property>
    </bean>

    <mvc:interceptors>
        <bean class="demo.DemoInterceptor"/>
    </mvc:interceptors>

</beans>
複製代碼

等價於java 配置: Root WebAppicationContext 配置mvc

@Configuration
@ComponentScan("demo")
public class DemoRootApplicationContextConfiguration {

    @Bean
    public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
        ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver();
        viewResolver.setDefaultViews(Lists.<View>newArrayList(mappingJackson2JsonView()));
        return viewResolver;
    }

    @Bean
    public MappingJackson2JsonView mappingJackson2JsonView() {
        MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
        jsonView.setExtractValueFromSingleKeyModel(true);
        return jsonView;
    }

    @Bean
    public DataSource dataSource() {
        // add data source config
        return null;
    }
}

複製代碼

servlet WebApplicationContext 配置

@ComponentScan("demo")
@Configuration
@EnableWebMvc
public class DemoWebMvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new DemoInterceptor());
    }

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}
複製代碼

這樣就能夠將web.xml、xxx-servlet去除掉了,不再用看到煩人的配置文件了。 固然 spring Mvc 還提供了一些抽象類來簡化配置工做,這裏爲了更方便的解釋java 配置的過程因此沒有直接使用。對這一部分有興趣的同窗能夠本身查看 AbstractAnnotationConfigDispatcherServletInitializer源碼。

相關文章
相關標籤/搜索