LoginSignup
9
4

More than 5 years have passed since last update.

spring-boot で開発環境でだけ有効なプロファイルを作る

Posted at

Spring Boot で開発環境だけで有効な Profile を作りたい。

環境 プロファイルが有効になってほしいか
IDE (IntelliJ) とかの組み込み機能で Debug/Run 実行 Yes
Gradle bootRun Yes
assemble した jar を実環境で run No

重要なのは、これをデフォルトで(特にユーザーが何かをする必要無く)やりたいって事です。

たどり着いた方法がこれ

  • spring-boot-devtools を入れておく
  • build 時に devtools jar を取り除く。 gradle なら以下の用に書く。
build.gradle
springBoot {
    excludeDevtools = true // fat jar にまとめたときには、devtools を取り除く
}

dependencies {
    // ...

    runtime 'org.springframework.boot:spring-boot-devtools:1.4.1.RELEASE'
    // 間違って使わないように、runtime スコープに入れた方がいい
}
  • spring-boot-devtools クラスが存在するかどうかで、条件分岐。
    例えば、
Application.java
@SpringBootApplication
public class Application {
    public static void main(String... args) throws Exception {
        final SpringApplication springApplication = new SpringApplication(Application.class);
        if (isDeveloping()) { // 開発環境では
            springApplication.setAdditionalProfiles("developing"); // developing プロファイルを追加
        }
        springApplication.run(args);
    }

    private static boolean isDeveloping() {
        return ClassUtils.isPresent("org.springframework.boot.devtools.settings.DevToolsSettings",
                                     ClassLoader.getSystemClassLoader());
        // DevToolsSettings クラスがあれば、開発中。
    }
}
9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4