Springboot学习之WebApplicationInitializer

本文介绍了Springboot如何使用JavaConfig替代web.xml配置启动SpringMVC,重点讲解了WebApplicationInitializer类的作用,以及如何通过注解配置消除传统XML配置文件,实现全注解的应用启动方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Springboot的一个重要功能就是可以消除几乎所有的配置文件,使用JavaConfig取而代之。

而Servlet3.0以后也推崇实用注解的方式取代web.xml配置文件,为了实现这一目的,Springboot提供了对应的类。

  • WebApplicationInitializer
  • SpringServletContainerInitializer

首先看一下使用web.xml配置文件的方式,我们是如何启动SpringMVC的servlet:

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

 而实用JavaConfig的方式则是这样的:

public class MyWebAppInitializer implements WebApplicationInitializer {
  
      @Override
      public void onStartup(ServletContext container) {
        //实用xml的方式配置SpringMVC
        XmlWebApplicationContext appContext = new XmlWebApplicationContext();
        //设置配置文件的位置
        appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
  
        //将DispatcherServlet实例添加到容器
        ServletRegistration.Dynamic dispatcher =
          container.addServlet("dispatcher", new DispatcherServlet(appContext));
        //设置启动顺序
        dispatcher.setLoadOnStartup(1);
        //设置映射路径
        dispatcher.addMapping("/");
      }
   }

这样一来,就实现了通过注解启动Spring容器。

然而,这种配置方式虽然消除了web.xml配置文件,Spring的配置文件还是存在,为了进一步将Spring的配置文件切换为注解的配置方式,只需要将XmlWebApplicationContext换成AnnotationConfigApplicationContext。

public class MyWebAppInitializer implements WebApplicationInitializer {
  
      @Override
      public void onStartup(ServletContext container) {
        // 创建Spring的root配置环境
        AnnotationConfigWebApplicationContext rootContext =
          new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfig.class);
  
        // 将Spring的配置添加为listener
        container.addListener(new ContextLoaderListener(rootContext));
  
        // 创建SpringMVC的分发器
        AnnotationConfigWebApplicationContext dispatcherContext =
          new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(DispatcherConfig.class);
  
        // 注册请求分发器
        ServletRegistration.Dynamic dispatcher =
          container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
      }
  
   }

通过以上的配置,就可以完全消除web应用中的配置文件,而以上方式其实也就是Springboot的使用方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值