GeekFactory

int128.hatenablog.com

spring.config.locationを複数指定した場合の優先順位

Spring Bootで --spring.config.location に複数のプロパティファイル(またはYAMLファイル)を指定した場合の優先順位を調べてみました。

TL;DR

  • --spring.config.location にはカンマ区切りで複数のプロパティファイルを指定できる。
  • 後に指定したプロパティファイルで値が上書きされる。
  • 例えば a.yaml,b.yaml,c.yaml を指定した場合、 c.yaml の定義値、 b.yaml の定義値、 a.yaml の定義値の順に検索される。

試してみた

Spring Boot 2.0.0.M7で試してみました。

@ConfigurationProperties("foo")
@RestController
class Example {
    var bar: String = "default.bar"
    var baz: String = "default.baz"

    @RequestMapping("/")
    fun index() = "bar=$bar, baz=$baz"
}

http://localhost:8080 でどんな値が返るか確認します。

何も指定しない場合

bar=default.bar, baz=default.baz

YAMLを1つ指定した場合

# a.yaml
foo:
  bar: a
  baz: x
--spring.config.location=a.yaml
bar=a, baz=x

YAMLを2つ指定した場合

# a.yaml
foo:
  bar: a
  baz: x
# b.yaml
foo:
  bar: b
  baz: y
--spring.config.location=a.yaml,b.yaml
bar=b, baz=y

YAMLを2つ指定したが未定義の値がある場合

# a.yaml
foo:
  bar: a
  baz: x
# b.yaml
foo:
  bar: b
--spring.config.location=a.yaml,b.yaml
bar=b, baz=x

YAMLを3つ指定したが未定義の値がある場合

# a.yaml
foo:
  bar: a
  baz: x
# b.yaml
foo:
  bar: b
  baz: y
# c.yaml
foo:
  bar: c
--spring.config.location=a.yaml,b.yaml,c.yaml
bar=c, baz=y

See Also