0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SpringBoot 設定ファイル(application.yml)を参照してみた

0
Posted at

概要

application.yml の設定値を参照する方法がとても簡単だったので紹介したいと思います。

サンプルコード

早速サンプルコードをどうぞ

application.yml

String、List、Map 型で設定値をそれぞれ定義する

yml:
  sample:
    str: abcde
    list:
      - list1
      - list2
      - list3
    map:
      key1: value1
      key2: value2
      key3: value3

YmlSampleProperties.java

設定ファイルに記載したフィールドを定義するクラス

@Component
@Data
@ConfigurationProperties(prefix = "yml.sample")
public class YmlSampleProperties {
    private String str;
    private List<String> list = new ArrayList<>();
    private Map<String, String> map = new LinkedHashMap<>();
}

SampleController.java

YmlSampleProperties クラスに定義した内容を取得し、
とりあえず System.out.println で表示確認する

@RestController
public class SampleController {

    @Autowired
    YmlSampleProperties ymlSampleProperties;

    @GetMapping("/ymlSample")
    public void getYmlData() {
        // String 取得
        String sampleStr = ymlSampleProperties.getStr();
        System.out.println(sampleStr);
        // List 取得
        List<String> sampleList = ymlSampleProperties.getList();
        System.out.println(sampleList);
        // Map 取得
        Map<String, String> sampleMap = ymlSampleProperties.getMap();
        System.out.println(sampleMap);
    }
}

動作確認

GET /ymlSample API をリクエストすると、
それぞれ設定値が標準出力で表示されることが確認できました!
※ jq は JSON 形式のデータを整形するコマンド

curl "http://localhost:8080/ymlSample"  | jq .
abcde
[list1, list2, list3]
{key1=value1, key2=value2, key3=value3}

String 型だけでなく、List や Map も設定ファイルに定義できるなんて便利!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?