淘先锋技术网

首页 1 2 3 4 5 6 7

SpringBoot web项目打成war包:

  • 修改pom文件打包方式:

  • 移除tomcat依赖或者将tomcat依赖scope改为provide:

    <!-- 方式1 -->
    <dependency>
    	<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <!-- 移除嵌入式tomcat插件 -->
        <exclusions>
        	<exclusion>
            	<groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    
    <!-- 方式2 -->
    <dependency>
    	<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    
  • 继承SpringBootServletInitializer,实现configure方法:

    • 方式一:引导类继承、实现

      @SpringBootApplication
      public class Application extends SpringBootServletInitializer {
          public static void main(String[] args) {
              SpringApplication.run(Application.class, args);
          }
          
          @Override
          protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
              return bulder.source(Application.class);
          }
      }
      
    • 方式二:新增加一个类继承、实现

      public class ServletInitializer extends SpringBootServletInitializer {
          @Override
          protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
              //此处的Application.class为带有@SpringBootApplication注解的引导类
              return bulder.source(Application.class);
          }
      }
      
  • 注意事项:

    • 使用外部Tomcat部署访问的时候,application.yml / application.properties中配置的server.port / server.servlet.context-path将失效,请使用tomcat的端口、webapps下项目名进行访问;

    • 为防止应用上下文所导致的项目访问资源加载不到的问题,建议pom.xml文件中标签下添加标签:

      <build>
      	<!-- 应与application.properties / application.yml中context-path保持一致 -->
          <fileName>war包名称</fileName>
          <plugins>
          	<plugin>
              	<groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-maven-plugin</artifactId>
              </plugin>
          </plugins>
      </build>