liguofeng29’s blog

個人勉強用ブログだっす。

Spring4 - BeanFactoryPostProcessor - PropertyPlaceholderConfigurer

PropertyPlaceholderConfigurerは、
propertiesファイルを読み取り、Springコンテナーのデータとして使える。

package app.propertyOverrideConfigurer;

public class Japanese{

    private int age; // 年齢
    private String name; // 名前

    public void setAge(int age) {
        this.age = age;
    }
    public void setName(String name) {
        this.name = name;
    }

    public void info() {
        System.out.println("名前 : " + this.name);
        System.out.println("年齢 : " + this.age);
    }
}
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <bean class=
        "org.springframework.beans.factory.config.PropertyOverrideConfigurer">
        <property name="locations">
            <list>
                <!-- propertieyファイル  -->
                <value>japanese.properties</value>
                <!-- 複数指定可能 -->
                <!--value>xxx.properties</value-->
            </list>
        </property>
    </bean>

    <!-- Bean定義 -->
    <!-- 属性を設定する必要がなく、propertyファイルから設定される -->
    <bean id="japanese" class="app.propertyOverrideConfigurer.Japanese" />
    
    <!-- XMLスキーマ利用 -->
    <!-- context-property-override location="classpath:japanese.properties"  -->
</beans>
package app.propertyOverrideConfigurer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestPropertyOverrideConfigurer  {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("PorpertyOverrideConfigurerBean.xml");

        // Bean取得
        Japanese p = context.getBean("japanese", Japanese.class);
        p.info();
    }
}
名前 : SATO
年齢 : 20