Spring Boot 2.4.0 でMultiple Propertyファイルを適用させる
Spring Boot 2.4になって、application.ymlの書き方がちょっと変わったのでメモ。色々便利になったようなのですが、k8sとか使っていないのであんまり恩恵がない 😑
基本設定をapplication-base.ymlに記述し、環境ごとの差異をそれぞれのapplication-xxx.ymlに記述します。
application.yml
# default spring: config: import: - classpath:application-base.yml --- spring: config: activate: on-profile: development import: - classpath:application-base.yml
application-base.yml
すべての環境で共通の設定を記述する
server: port: 8081 shutdown: graceful
application-development.yml
some.property.label: development
application-default.yml
local起動の場合 (特にprofileを指定しない場合) defaultになります。
some.property.label: default
configuration
テスト用に適当なConfigurationを用意
@Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(SomeProperty::class) class SomeConfiguration( private val prop: SomeProperty ) { fun prop() = prop.label } @ConfigurationProperties("some.property") @ConstructorBinding class SomeProperty( val label: String = "" )
@RestController class ConfigTestController( val config: SomeConfiguration ) { @GetMapping("test") fun test(): Mono<String> = mono { config.prop() } }
コンテナにします
$ ./gradlew bootBuildImage
defaultで起動
$ docker run -m "1024M" -it -p 8081:8081 --rm demo:0.0.1-SNAPSHOT $ curl http://localhost:8081/test -> default
developmentで起動
$ docker run -m "1024M" -it -p 8081:8081 -e "SPRING_PROFILES_ACTIVE=development" --rm demo:0.0.1-SNAPSHOT -> The following profiles are active: development $ curl http://localhost:8081/test -> development
上書きしたい場合
以前と同様に、後からimportしたproperty fileが一番強くて、設定をoverrideします。
application-override.yml
server: port: 8080
application.yml
--- spring: config: activate: on-profile: development import: - classpath:application-base.yml - classpath:application-override.yml
$ docker run -m "1024M" -it -p 8080:8080 -e "SPRING_PROFILES_ACTIVE=development" --rm demo:0.0.1-SNAPSHOT -> Netty started on port(s): 8080
前より書き方が面倒になった気もするが、これであっているのだろうか 😑
profile.groupsを使うよりはこっちのほうがまだ楽だと思うけど、情報待ちデス