Spring4 - BeanFactoryPostProcessor - PropertyPlaceholderConfigurer
PropertyPlaceholderConfigurerは、
propertiesファイルを読み取り、Springコンテナーのデータとして使える。
package app.beanFactoryPostFrocessor; 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.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <!-- propertieyファイル --> <value>japanese.properties</value> <!-- 複数指定可能 --> <!--value>xxx.properties</value--> </list> </property> </bean> <!-- Bean定義 --> <bean id="japanese" class="app.beanFactoryPostFrocessor.Japanese" p:name="${name}" p:age="${age}" /> <!-- XMLスキーマ利用 --> <context:property-placeholder loaction="classpath:japaense.properties" /> </beans>
japanese.properties
name=SATO age=20
package app.beanFactoryPostFrocessor; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestPropertyPlaceholderConfigurer { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("PorpertyPlaceholderConfigurerBean.xml"); // Bean取得 Japanese p = context.getBean("japanese", Japanese.class); p.info(); } }
名前 : SATO 年齢 : 20