SpringBootでConfigファイルから値を読み込むサンプルを紹介します。
SpringBootでのConifgの扱い
SpringBootプロジェクト内にあるsrc/main/resources配下にある *.yml や *.properties ファイルをConfigファイルとして読み込みます。
STSでプロジェクトを作成した場合、自動的にapplication.propertiesができているかと思います。
SpringBootでのConfigファイルの正確な仕様については、以下などをご確認ください。
Spring Bootがプロパティファイルを読み込む方法に一同驚愕!! | Tagbangers Blog
Config読み込みのサンプル
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class TestClass {
@Value("${sample.value}")
public String configValue;
}
sample.value: SampleValue
@RestController
public class HelloController {
@Autowired
private TestClass testClass;
@RequestMapping("/")
public String index() {
return testClass.configValue; // return "SampleValue"
}
コンテナ(@Beanや@Componentなどが記載されたクラス)のフィールドに@VlueアノテーションをつけることでConfigから値を読み込むことができます。
Staticフィールドへの読み込み
Staticフィールドに読み込みたい場合は、上記の方法だとうまくいきません。
コンストラクタでセットしてやる必要があります。
@Component
public class TestClass {
private static String configValue;
@Autowired
public TestClass(@Value("${sample.value}") String sampleValue) {
TestClass.configValue = sampleValue;
}
public String getConfigValue() {
return TestClass.configValue;
}
}
コンストラクタに@Autowiredをつけることで、Bean化するときにコンストラクタが処理されます。
コンストラクタの引数でConfigから値を読み込み、それをフィールド変数に設定しています。
この方法であれば、Static変数にもConfigから値を設定することができます。