首页 > 解决方案 > Spring Boot 应用程序在 web.xml 中启动应用程序初始化 servlet

问题描述

@Given Web.xml 带有所有 servlet 映射和 contextConfigLocations 以加载 spring bean。

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringBootAppWithWebxml</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring/appServlet/spring-context-config.xml
    </param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        /WEB-INF/spring/appServlet/servlet-context.xml
      </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
    <servlet>
        <servlet-name>sampleServlet</servlet-name>
        <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>sampleServlet</servlet-name>
        <url-pattern>/sample/*</url-pattern>
    </servlet-mapping>
    </web-app>

如何使用 SpringBoot 应用程序加载这个 web.xml 和相应的 servlet 和 contextConfig?

Web.xml 位于模块 A 中,调用应用程序 B 将模块 A 作为依赖项。

我的 springBootapp 是

@SpringBootApplication(scanBasePackages = {"com.test.package"})
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class StarterApp{

    public static void main(String[] args) {
        SpringApplication.run(StarterApp.class);
    }

}

标签: javaspringspring-boot

解决方案


Spring-boot 通常更喜欢基于注释的配置而不是基于 xml 的配置。默认情况下,Springweb.xml通常会存在,src/main/webapp/WEB-INF并且会被 spring 自动占用。

请参阅此帖子以获取更多详细信息:

Spring Boot 中的 DispatcherServlet 和 web.xml


推荐阅读