Spring Bootでpropertiesファイルの値を取得する方法を調べたので記述していきます。毎回忘れる(笑) 今回はEnvironmentを使用して取得する方法とproperty-placeholderを使用して取得する方法を紹介していきたいと思います。
プロパティファイルの項目値取得方法
最初にテスト用にプロパティファイルを以下のように設定していきます。testProperiesColumnに値を設定しているだけです。
プロパティファイル
//application.properties
testPropertiesColumn = プロパティファイルの値だよん
Enviromentを使用した取得方法
Enviromentを使用したプロパティファイルの取得方法を紹介していきます。
まず、プロパティファイル読込用のクラスを作成していきます。クラス宣言に@Configurationと@PropetySourceを追加し、取得したいプロパティファイルを定義します。
クラスパスから取得する場合は【classpath:】、物理パスから取得する場合は【file:~】と記述します。
例外を無視したいときは「ignoreResourceNotFound=true」を設定します。プロパティの値を保持するクラスEnviromentを定義します。
Enviromentは同じキーがあると上書きしてしまうので注意が必要です。
プロパティファイル読込用クラス
//ApplicationProperties.java
@Configuration
@PropertySource("classpath:application.properties", ignoreResourceNotFound=true)
public class ApplicationProperties {
@Autowired
private Environment env;
public String get(String key) {
return env.getProperty(key);
}
}
プロパティファイル値を取得するクラス
//TestController.java
@Controller
public class TestController {
@Autowired
ApplicationProperties applicationProperties;
@GetMapping("/test")
public String init(@ModelAttribute("testForm") ResultsSummaryForm resultForm) throws AppException {
log.info(applicationProperties.get("resultSummaryFolderPath"));
return "/page";
}
}
property-placeholderを使用した取得方法
AppicationContext.xmlにproperty-placeholderを指定します。locationにプロパティファイルのパスを設定します。
アプリケーション設定ファイルに読込設定追加
//ApplicationContext.xml
<context:property-placeholder location="classpath:/application.properties"/>
プロパティファイル値を取得するクラス
@Valueアノテーションで取得したいプロパティのキーを指定するだけ、これだけで取得できるので便利な世の中です。
@Controller
public class ResultsSummaryController {
@Autowired
ApplicationProperties applicationProperties;
@Value(value = "${testPropertiesColumn}")
String path;
@GetMapping("/test")
public String init(@ModelAttribute("testForm") ResultsSummaryForm resultForm) throws AppException {
log.info(path);
return "/page";
}
}