Springboot ymlプロファイル値の取得


yml
Springbootはpropertiesを使用して構成項目の設定を行うか、yml構文を使用して構成項目を設定することができます.
構成クラスを追加
ここの注釈に注意
@ConfigurationProperties(prefix = "person")
@Component

このクラスが構成クラスであることを示し、構成で使用でき、personとして定義されています.
package com.example.springbootdemo1.model;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@ConfigurationProperties(prefix = "person")
@Component
public class person {
     
    private String name;

    private Map<String,Object> maps;

    private List<String> lists;

    private dog dog;

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

    public Map<String, Object> getMaps() {
     
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
     
        this.maps = maps;
    }

    public List<String> getLists() {
     
        return lists;
    }

    public void setLists(List<String> lists) {
     
        this.lists = lists;
    }

    public com.example.springbootdemo1.model.dog getDog() {
     
        return dog;
    }

    public void setDog(com.example.springbootdemo1.model.dog dog) {
     
        this.dog = dog;
    }

    @Override
    public String toString() {
     
        return "person{" +
                "name='" + name + '\'' +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog.toString() +
                '}';
    }
}


yml構成を使用するにはpomにインポートする必要があります
 <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
        dependency>

テストをtestで行うため、この依存をインポートする必要があります.そうしないと、failed to resolve org.junit.platformのエラーが表示されます.
 <dependency>
            <!-- this is needed or IntelliJ gives junit.jar or junit-platform-launcher:1.3.2 not found errors -->
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <scope>test</scope>
        </dependency>

yml構成内容
yml構文フォーマットはスペースで値を区別します.スペースに注意してください.
server:
  port: 8080
person:
  name:   
  maps: {
     k1: v1,k2: v2}
  lists:
    - hello
    - world
    - how
  dog:
    name: '   '

テスト
package com.example.springbootdemo1;

import com.example.springbootdemo1.model.person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Springbootdemo1ApplicationTests {
     

    @Autowired
    com.example.springbootdemo1.model.person person;
    @Test
    void contextLoads() {
     
        System.out.println(person);

    }

}


person{name=‘小明’,maps={k 1=v 1,k 2=v 2},lists=[hello,world,how],dog=dog{name=‘ハスキー’}}
yml構成項目の内容が取得できることがわかります.