私のspring学習ノート13-コンテナ拡張点のP r o p e r tyPlaceholderConfigurer

3966 ワード

P r o p e r t y PlaceholderConfigurerはbeanファクトリのバックグラウンドプロセッサの実装、すなわちBeanFactoryPostProcessorインタフェースの実装です.BeanFactoryPostProcessorについてはBeanPostProcessorと似ています.他の場所で紹介します.PropertyPlaceholderConfigurerは、コンテキスト(プロファイル)のプロパティ値を別の標準java Propertiesファイルに配置できます.これでは、xmlプロファイルを変更することなくpropertiesファイルを変更するだけです.役割は何ですか.いくつかの属性値は常に変更する必要はありませんが、いくつかの属性値はいつでも変更される可能性があります.よく変更される属性値を別のファイルに置くと、プログラムの使用も便利になります.次の例では、PropertyPlaceholderConfigurerを理解します.まず、プロファイルです.コードは次のとおりです.
<?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:util="http://www.springframework.org/schema/util"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">
 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location" value="propertyPlaceHolder.properties"/>
    </bean>
    <bean id ="student" class="co.jp.beanFactoryPost.Student">
     <property name="name">
      <value>${name}</value>
     </property>
     <property name="age">
      <value>${age}</value>
     </property>
     <property name="birth">
      <value>${birth}</value>
     </property>
    </bean>
</beans>

このプロファイルで最も重要なのは、次のコードです.
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location" value="propertyPlaceHolder.properties"/>
</bean>

PropertyPlaceholderConfigurerは、locationで設定されたプロパティファイルを読み込み、propertiesファイルの値を${name},${age},${birth}に設定して依存注入を完了します.対応するpropertiesファイルの定義は以下の通りです:name=xiaohailinage=27 birth=19820123ここで使用するstudent bean、classのコードは以下の通りです:比較的簡単で、主にget、set方法です
package co.jp.beanFactoryPost;
public class Student {
    private String name;
    private String age;
    private String birth;
    public void setName(String name)
    {
        this.name = name;
    }
    public void setAge(String age)
    {
        this.age = age;
    }
    public void setBirth(String birth)
    {
        this.birth = birth;
    }
    public String getName()
    {
        return this.name;
    }
    public String getAge()
    {
        return this.age;
    }
    public String getBirth()
    {
        return this.birth;
    }
}

次に、public class PropertyHolderPlaceDemo{
    public static void main(String[] args) {
       
        ApplicationContext ctx = new ClassPathXmlApplicationContext("propertyPlaceHolder.xml");
       
        Student student = (Student) ctx.getBean("student");
        System.out.println(student.getAge());
        System.out.println(student.getBirth());
        System.out.println(student.getName());  
    }
}

 
詳細については、Springチュートリアルhttp://www.itchm.com/forum-59-1.htmlを参照してください.