SpringBootで設定ファイルの値を取得する方法は何ですか?
Spring Bootでは、@ConfigurationPropertiesアノテーションを使用して、設定ファイルの値を取得することができます。
- application.propertiesやapplication.ymlファイルで設定項目を定義します。例えば:
アプリケーションのプロパティ
myapp.name=My Application
myapp.version=1.0
アプリケーションの設定ファイル、application.yml
myapp:
name: My Application
version: 1.0
- 設定クラスを作成し、@ConfigurationPropertiesアノテーションを使用して設定項目をバインドします。例えば:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String name;
private String version;
// 省略getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
- 必要な場所で設定値を使用する際には、依存性注入を使用して設定クラスのインスタンスを取得します。例えば:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private final MyAppProperties appProperties;
@Autowired
public MyController(MyAppProperties appProperties) {
this.appProperties = appProperties;
}
@GetMapping("/app-info")
public String getAppInfo() {
return appProperties.getName() + " " + appProperties.getVersion();
}
}
上記の例では、MyAppPropertiesクラスは@ConfigurationPropertiesアノテーションのprefix属性を使用して、設定項目の接頭辞を指定しています。Spring Bootは、自動的にこの接頭辞で始まる設定項目の値を、このクラスの対応するプロパティにバインドします。そして、MyControllerクラスでは、コンストラクタを介してMyAppPropertiesのインスタンスをインジェクションし、そのインスタンスを使用して設定値を取得します。