1. 程式人生 > >Spring Boot 專案釋出到 Tomcat 伺服器

Spring Boot 專案釋出到 Tomcat 伺服器

特別說明: tomcat版本必須7以上,我之前就是專案main方法執行一切正常,但把war包部署到tomcat6上,訪問就報404找不到請求的路徑。

第 1 步:將這個 Spring Boot 專案的打包方式設定為 war。

<packaging>war</packaging>

這裡還要多說一句, SpringBoot 預設有內嵌的 tomcat 模組,因此,我們要把這一部分排除掉。
即:我們在 spring-boot-starter-web 裡面排除了 spring-boot-starter-tomcat ,但是我們為了在本機測試方便,我們還要引入它,所以我們這樣寫:

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <!-- 打包部署到tomcat上面時,不需要打包tmocat相關的jar包,否則會引起jar包衝突 -->
      <exclusions>
        <exclusion>
            <groupId
>
org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>
spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> </dependencies>

第 2 步:提供一個 SpringBootServletInitializer 子類,並覆蓋它的 configure 方法。我們可以把應用的主類改為繼承 SpringBootServletInitializer。或者另外寫一個類。

@Configuration  
@ComponentScan  
@EnableAutoConfiguration  
public class Application extends SpringBootServletInitializer {

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

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

注意:部署到 tomcat 以後,訪問這個專案的時候,須要帶上這個專案的 war 包名。
另外,我們還可以使用 war 外掛來定義打包以後的 war 包名稱,以免 maven 為我們預設地起了一個帶版本號的 war 包名稱。例如:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <warName>springboot</warName>
    </configuration>
</plugin>