zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    git fetch, merge, pull, push需要注意的地方
    记录一次数据库驱动配置引发的惨案
    IntelliJ Idea 常用快捷键列表
    数据库设计范式
    windows下mysql服务常用操作
    开源协议知多少
    Error creating bean
    Validation failed for query for method
    Not supported for DML operations
    404
  • 原文地址:https://www.cnblogs.com/SunSAS/p/12268120.html
Copyright © 2011-2022 走看看