ぺーぺーSEのブログ

備忘録・メモ用サイト。

JavaやSpringのプロパティファイルの読み込み

Java標準のプロパティファイルの読み込み

Springのプロパティファイルの読み込み

■bean定義ファイル内の「${key}」個所をプロパティファイルから参照する方法
「key=value」形式で書かれたプロパティファイルを下記のようにbean定義ファイルから読み込む。
※Spring 2.5.6-SEC01の例(Spring3系でも同様)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
        <value>file:[プロジェクトルートからプロパティファイルのパス]</value>
        <value>file:[プロパティファイルへの絶対パス]</value>
        <value>[クラスパス配下のプロパティファイル、webアプリだとclasses配下]</value>
        <value>file:resource/hoge.properties</value>
        <value>file:/[何かパス1]/[何かパス2]/.../[何かパスn]/hoge.properties</value>
        <value>hoge.properties</value>
      </list>
    </property>
    <property name="searchSystemEnvironment" value="true"/>
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="ignoreResourceNotFound" value="true" />
  </bean>
</beans>
  • 内について
    • keyが被った場合はより下で設定したのプロパティファイルの設定が上書きされる
    • 環境変数VM引数を使用する設定(デフォルトtrue)
    • 環境変数VM引数(-Dkey=value)がある場合はこちらを優先する設定
    • 「${key}」が解決できなくてもエラーを吐かない設定
    • プロパティファイルが見つからなくてもエラーを吐かない設定