Converting a Spring Boot JAR Application to a WAR

f:id:Naotsugu:20150110034558p:plain

Getting Started · Converting a Spring Boot JAR Application to a WAR

Spring Boot には強力な2つのプラグインがあります。

  • spring-boot-gradle-plugin
  • spring-boot-maven-plugin

これらは本質的に同等の機能を有しており、Spring Boot アプリケーションのコマンドラインからの起動と、実行可能 JAR の作成を提供します。これは実行フェーズを説明した全てのガイドで記載していることです。

しかし多くの人は、コンテナにデプロイするWARファイルの生成方法も知りたいでしょう。先のプラグインはどちらも同様に上手くこなします。 基本的には、WARファイルの生成に関する設定を変更し、組み込みコンテナの依存設定を provided と宣言すれば良いです。これにより、組み込みのコンテナの依存がWARファイルに含まれなくなります。

Gradle の場合は

...
apply plugin: 'war'

war {
    baseName = 'myapp'
    version =  '0.5.0'
}

repositories {
    jcenter()
    maven { url "http://repo.spring.io/libs-snapshot" }
}

configurations {
    providedRuntime
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
    ...
}

war プラグインを使い、組み込みコンテナの依存を providedRuntime とします。

Spring Boot はサーブレット3.0 のコンテナで動作します アプリケーションベースクラスとして SpringBootServletInitializer を使うことで、Spring の Servlet 3.0 サポートがデプロイ時に有効となります。

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

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        // Customize the application or call application.sources(...) to add sources
        // Since our example is itself a @Configuration class we actually don't
        // need to override this method.
        return return application.sources(Application.class);
    }

}