LoginSignup
4
2

More than 5 years have passed since last update.

Spring Boot の設定ファイルを理解する

Posted at

大体この辺に書いてあるが難しいのでまとめる
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

YAML で記述しても内部的には Java Properties になる

Spring Boot が内部的で Java Properties で保持しているため、最終的な表現は Java Properties ベースとなる。
以下はどちらも YAML であり、 YAML としてはまったく意味が異なるが Spring Boot の設定ファイルにおいては同じ結果となる。

myapp:
    value: hello
myapp.value: hello

よくある事例として spring.profiles を設定しつつ spring.profiles.include を設定したいときは以下のように記述できる

---
spring.profiles: dev
spring:
    profiles:
        include:
            - local-db

spring.profiles.active は一度しか読み込まれない

spring.profiles.active が未定義のときのみ、そのプロファイルの設定がロードされる。
以下のように指定すると include したプロファイルに記述したプロファイル bar をロードすることができるがやる意味は特にないしわかりにくくなるだけなので、 active を指定するのは applicaiton.yml と application-default.yml のみにとどめたほうがいいだろう。

application.yml
---
spring.profiles: default
spring.profiles.include:
  - foo

---
spring.profiles: foo
spring.profiles.active: bar

プロファイルはタグのように扱える

spring.profile.active は複数設定することができる。また、ここで指定した profile はそれに対応した設定ファイルが存在している必要もない。
これを利用すると DB の設定などを別プロファイルに切り離しておき、 active や include にそのプロファイルを追加指定することで切り替えたりするようなことができる。

例えばテストに用いるデータベースを手元で実行するときはローカルを、 CI で実行するときは特定の DB を使うなどとしたいときは以下のように記述できる

application.yml
---
spring.profiles: default
spring.profiles.active: test

---
spring.profiles: test
spring:
    datasource:
        # local db settings

---
spring.profiles: ci
spring.profiles.include:
    - ci-db

---
spring.profiles: ci-db
spring:
    datasource:
        # ci db settings

CI のタスクで SPRING_PROFILES_ACTIVE=test,ci と指定することにより接続先 DB を CI 用のものに変更できる
上記では test, ci, ci-db がプロファイルとして spring boot に読み込まれる
このように記述していくことのメリットとして読み込まれたプロファイルが @Profile Annotation などで指定できるため細かく切り替えることができるようになる

logback-spring.xml においても springProfile タグを使って環境ごとにディレクトリや appender を変更することがままあるため非常に相性が良い

4
2
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
4
2