• Spring Boot源码(一):去除web.xml


    访问https://spring.io/

     

     spring boot中:

    public class MyWebApplicationInitializer implements WebApplicationInitializer {
    
        @Override
        public void onStartup(ServletContext servletCxt) {
    
            // Load Spring web application configuration
            AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
            ac.register(AppConfig.class);
            ac.refresh();
    
            // Create and register the DispatcherServlet
            DispatcherServlet servlet = new DispatcherServlet(ac);
            ServletRegistration.Dynamic registration = servletCxt.addServlet("app", servlet);
            registration.setLoadOnStartup(1);
            registration.addMapping("/app/*");
        }
    }

    在原来的spring mvc中web.xml:

    <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>

    参考官方文档:

    它的作用就是注册和初始化DispatcherServlet

    其中:

    <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>

    而spring boot中的这四句代码与上面一样:

     不过web.xml中还可以向容器中注入三大组件,servlet,filter,listener

    可以通过@WebServlet,@WebFilter,@WebListener注解方式注入。

    不过spring boot中用的是SPI来注入,关于怎么注入,下篇再说。

    Spring Boot源码(二):SPI去除web.xml

  • 相关阅读:
    java线程系列---Runnable和Thread的区别 (转载)
    JAVA基础(多线程Thread和Runnable的使用区别(转载)
    error: undefined reference to 'property_set (转载)
    Django基本命令
    第三篇数据库与ORM
    PyCharm下创建并运行我们的第一个Django项目
    第二篇MTV模型、基本命令、简单配置
    第一篇web框架
    Django框架全面讲解
    MySQL的异常问题
  • 原文地址:https://www.cnblogs.com/SunSAS/p/12268120.html
Copyright © 2020-2023  润新知