Spring Roo : プロパティを扱う

Spring のアプリケーションの設定を、.propertiesファイルに持たせて参照したい、という場合の設定方法です。古い人間なのでそういうものはapplicationContext.xmlに設定するのかなあ、と思っていたのですが。

Spring Roo でアプリケーションを作成すると、applicationContext.xmlには自動で以下の設定がされています。

	<!--
		This will automatically locate any and all property files you have
		within your classpath, provided they fall under the META-INF/spring
		directory. The located property files are parsed and their values can
		then be used within application context files in the form of
		${propertyKey}.
	-->
	<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>

これ、ざっくり訳すと、

  • クラスパスのMETA-INF/spring/ ディレクトリにあるpropertiesファイルを自動的に読み込む
  • 読み込んだプロパティファイルで定義されたプロパティは、${propertyKey}という形式で、application contextにあるファイルから参照可能

なのだそうです。さらに、クラスファイルから参照する場合は@Valueアノテーションを使えばよさそうなので、やってみました。

  • src/main/resources/META-INF/spring ディレクトリにmyproperty.propertiesファイルを作成。以下を設定
myproperty.key=value
  • クラスには以下のように記述
  @Value("${myproperty.key}")
  private String key;

これで実行すると、keyには値"value"が入っています。なんとなく、@Valueなどは、@ServiceなどがアノテーションされたSpring管理のクラスでないと効かないような気がするのですが、どうなのでしょう。やってみてないからわからない(というか、自動Injectionの仕組みがわかっていない)ですが。