m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

Spring Bootで設定ファイルのデータを取得する

設定ファイルというと

iniファイルとかcsvファイルとか独自に用意したプロパティファイルとかあります。
プログラム内の固定値とかではなく実行環境(開発、本番)で設定値が変化する場合に切り替えたいもの

Spring Bootの場合は

application.properties
が基本らしい
他のファイルとしてはymlもあるみたいですね。

設定する情報とは

サーバのポートやデータベースの接続情報などを設定して使うことが基本です。
ですが独自の設定情報を保持したいこともあります。

ので独自の設定値を取得できるかテストします。

サンプル

application.properties
# sample
sample.test1=aaaaaaaaa
sample.test2=222222222
sample.test3=hogehoge

こんな感じ…

取得処理

SampleController.java
package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {
	
	@Autowired
	private Environment eivironment;
	
	@RequestMapping(value = "/sample/getProperty/{key}", method = { RequestMethod.GET } )
	public String test1(@PathVariable String key) {
		return eivironment.getProperty("sample." + key);
	}
	
}

※ Environmentを使用する。

結果

f:id:m_shige1979:20170109222612p:plain
取得できました
設定ファイル名は仕方がないので別途定数で管理しましょう。

今回はここまでですm(_ _)m