spring boot 項目由jar轉war

spring boot 項目由jar轉war

spring boot 快速構建web項目,官方推薦使用jar類型內嵌tomcat等容器的方式啓動及部署,使用過程中難免要使用外部容器部署,可以通過以下方式轉化:

第一步:

轉化jar類型項目爲可部署的war文件的第一步是提供一個SpringBootServletInitializer子類和覆蓋它的configure方法。通常做法是,讓應用程序的入口類繼承SpringBootServletInitializer:

@SpringBootApplication
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);
    }

}

注意:不同版本繼承的SpringBootServletInitializer類不同
1.3.3版本爲org.springframework.boot.context.web.SpringBootServletInitializer
1.4.1版本爲org.springframework.boot.web.support.SpringBootServletInitializer

第二步:

若項目使用maven並且pom.xml繼承了spring-boot-starter-parent,需要更改pom.xml中的packagingwar類型:

<packaging>war</packaging>

若使用Gradle:


apply plugin: 'war'

第三步:

最後一步是確保嵌入servlet容器不干擾外部servlet容器部署war文件。需要標記嵌入servlet容器的依賴爲provided
若使用Maven:

<dependencies>
    <!-- … -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- … -->
</dependencies>

若使用Gradle:

dependencies {
    // …
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    // …
}

若war在部署到容器中時遇到Project facet Cloud Foundry Standalone Application version 1.0 is not supported.錯誤;
解決辦法: 項目右鍵Build Path -> Configure Build Path -> Project facet -> 勾掉Cloud Foundry Standalone Application
這裏寫圖片描述
重新編譯打包即可。

參考 :

[Spring Boot指南(Spring Boot Reference Guide)]

的以下兩小節
81.1 Create a deployable war file
63.2 Packaging executable jar and war files

我是結尾。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章