javaでのymlの設定値の取得方法

YAMLファイルの設定値を取得するには、Spring Bootが提供する@ConfigurationPropertiesアノテーションを使用します。YAML設定値を取得する手順は次のとおりです。

  1. Spring Bootアプリケーションの設定クラスに@ConfigurationPropertiesアノテーションを追加して、YAMLファイルのプレフィックスを指定します。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "your-prefix")
public class YourConfigClass {
    private String yourProperty;

    public String getYourProperty() {
        return yourProperty;
    }

    public void setYourProperty(String yourProperty) {
        this.yourProperty = yourProperty;
    }
}
  1. YAMLファイルに設定項目を定義し、Javaクラスの属性に対応するキーを使用する。
your-prefix:
  your-property: value
  1. アプリケーションにおいて、@Autowiredアノテーションを使用してコンフィグクラスを自らのクラスに注入し、コンフィグ値にアクセスする。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class YourApplication {
    @Autowired
    private YourConfigClass yourConfigClass;

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }

    public void someMethod() {
        String propertyValue = yourConfigClass.getYourProperty();
        // 使用配置值进行操作
    }
}

その結果、YAML ファイルから設定値を取得してアプリケーションで使用するようになります。

bannerAds