Environmentを利用して動的にプロパティファイルから値を取得する。
バージョン
spring boot 2.0.3.RELEASE
プロパティファイル
application.properties
sample.name=hoge
sample.age=20
Environmentを利用したConfigurationクラス
EnvironmentをインジェクションしてgetPropertyメソッドを呼び出す。
SampleProperty.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
// @PropertySourceでプロパティファイルの場所を指定
@PropertySource("classpath:/application.properties")
public class SampleProperty {
// Environmentをインジェクション
@Autowired
private Environment env;
public String get(String key) {
// Environmentからプロパティ値を取得
return env.getProperty("sample." + key);
}
}
RestController(Configurationクラスを呼び出すクラス)
URLに含まれるパスをkeyとしてConfigurationクラスから値を取得する。
SampleController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@Component
@RestController
public class SampleController {
@Autowired
private SampleProperty prop;
@GetMapping(path = "/user/{key}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getUser(@PathVariable String key) {
String result = prop.get(key);
if (result == null) {
result = "値が取得できませんでした。";
}
return result;
}
}
動作確認
ブラウザからhttp://localhost:8080/user/name にアクセス
ブラウザからhttp://localhost:8080/user/age にアクセス