[Java][Spring] プロパティファイルを読み込んでマッピングする。

2016.07.28

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

SpringではJavaの内容だけではなく、プロパティファイルを作って読み込む事もできるらしいので調べました。
小ネタですが、備忘録として書いておきます。

環境

MAC OSX 10.10.5 Yosemite
Eclipse Mars
Java 8
Spring Boot 1.3.6.RELEASE

コードの目的

プロパティファイルに書かれた内容を読み込んで標準出力をする。

コード

プロパティファイル

propertiesとymlのどちらでも大丈夫です。

application.propertiesの場合

test.oneText  = properties(1-1)
test.two-text = properties(1-2)
property.prop = properties(2)

application.ymlの場合

test:
  oneText: properties(1-1)
  two-text: properties(1-2)
property:
  prop: properties(2)

プロジェクトをSpring Starter Projectで作成すると、src/main/resourcesに生成されます。
この内容を標準出力していきます。
ちなみに上記のように、キャメルケース・スネークケース・チェインケースにも対応しています。

プロパティを読み込むコンポーネント

package com.properties.test;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix="test")
public class Test {
	private String one;
	private String two;
}

コントローラーから呼ばれるクラス。
9~10行目、フィールド変数のGetter/Setterが必要なので、lombokの@Getter/@Setterで生成。
11行目、コンポーネント化。@Autowiredで変数にインジェクション可能になります。
12行目、プレフィックスに"test"を指定。これでapplication.propertiesの"test.one"と"test.two"を呼べます。

コントローラー

package com.properties.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoadController {

	@Autowired
	private Test test;
	
	@RequestMapping(value="/1", method=RequestMethod.GET)
	public String load2() {
		StringBuilder builder = new StringBuilder();
		builder.append("test.one = ");
		builder.append(test.getOne());
		builder.append(", ");
		builder.append("test.two = ");
		builder.append(test.getTwo());

		return builder.toString();
	}
	
	@Value("${property.prop}")
	private String testprop;
	
	@RequestMapping(value="/2", method=RequestMethod.GET)
	public String load1() {
		return testprop;
	}
	
}

クラス内のメソッドが2個有り、それぞれ取得方法が異なります。

8行目、まずは実行結果を見るための設定をします。

取得方法1
11~12行目、作成したコンポーネントをBeanにインジェクション。
16~21行目、プロパティファイルの値を取得し、StringBuilderにまとめます。

取得方法2
26~27行目、方法1とは違い、アノテーションで直接プロパティを指定しています。
31行目、メソッド内で返します。

実行結果

curlで実行した結果を見てみます。

$ curl http://localhost:8080/1
test.one = properties(1-1), test.two = properties(1-2)
$ curl http://localhost:8080/2
properties(2)

application.propertiesに書いた設定が読み込まれました。

さいごに

これでプロパティファイルにURL、ディレクトリ、ファイルなどを書いて動的に対応する事ができます。