Spring Boot:Deploy WAR file to Tomcat

578 阅读1分钟

原文地址www.mkyong.com/spring-boot…

For Spring Boot WAR deployment, you need to do three steps:

  1. Extends SpringBootServletInitializer.
  2. Marked the embedded servlet container as provided.
  3. Update packaging to war.

1. Extends SpringBootServletInitializer

Make the existing @SpringBootApplication class extends SpringBootServletInitializer

1.1 Classic Spring Boot JAR deployment. (Update this file to support WAR deployment)

SpringBootWebApplication.java

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootWebApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }

}

1.2 Spring Boot WAR deployment.

SpringBootWebApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringBootWebApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }

}

/*@SpringBootApplication
public class SpringBootWebApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }

}*/

If you create a extra SpringBootWebApplication class for deployment, make sure tell Spring Boot which main class to start :

pom.xml

  <properties>
        <start-class>com.mkyong.NewSpringBootWebApplicationForWAR</start-class>
  </properties>

2. Marked the embedded servlet container as provided

pom.xml

<dependencies>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>

	<!-- marked the embedded servlet container as provided -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-tomcat</artifactId>
		<scope>provided</scope>
	</dependency>

</dependencies>

3. Update packaging to war

pom.xml

  <packaging>war</packaging>

Done, mvn package and copy the $project/target/xxx.war to Tomcat for deployment.