以下はSpringFrameworkを利用してプロパティファイルを外部から読み込む方法です。
読み込むプロパティファイルを外部に定義できるのでプロパティファイルが増えた場合のソース改修の無駄が省けます。
applicationContext.xml
以下のコンテキストファイルでは、myPropertyというbeanIdのPropertiesFactoryBeanに
「application1.properties」と「application2.properties」の2つのプロパティファイルを食わせています。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="myProperty"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:application1.properties</value>
<value>classpath:application2.properties</value>
</list>
</property>
</bean>
</beans>
利用するpropertiesファイル
application1.properties
hoge=ほげ。
application2.properties
foo=ふー。
applicationContext.xmlのbeanIdで定義した「myProperty」を利用してみる。
// コンテキストファイルの在り処(配列で複数指定可能)
String[] files = { "applicationContext.xml" };
// アプリケーションコンテキストを生成
ApplicationContext ctx = new ClassPathXmlApplicationContext(files);
// "myProperty"をキーにPropertiesを取得する
Properties p = (Properties) context.getBean("myProperty");
// 出力してみる。
System.out.println("hoge: " + p.getProperty("hoge"));
System.out.println("foo: " + p.getProperty("foo"));
出力結果
以下のように出力されれば成功です。
hoge: ほげ。
foo: ふー。