在Spring的Bean裝配文件中配置組件是合適的,但類似于數據庫細節,隊列主題細節等應該分離出來,這時我們可以使用Spring的PropertyPlaceholderConfigurer從外部屬性文件中裝載一些配置信息,使用起來很簡單,請參考下例:
http://www.tkk7.com/Files/heyang/SpringProperties20090926133054.rar
注意加入必要的包:commons-logging-1.0.4.jar,log4j-1.2.14.jar,spring.jar
兩個配置的內容:
person1.properties
person1.id=001
person1.name=Andy
person1.password=123456
person2.properties
person2.id=002
person2.name=Bill
person2.password=111111
Bean裝配文件的內容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>person1.properties</value>
<value>person2.properties</value>
</list>
</property>
</bean>
<bean id="person1" class="com.heyang.Person" >
<property name="id">
<value>${person1.id}</value>
</property>
<property name="name">
<value>${person1.name}</value>
</property>
<property name="password">
<value>${person1.password}</value>
</property>
</bean>
<bean id="person2" class="com.heyang.Person" >
<property name="id">
<value>${person2.id}</value>
</property>
<property name="name">
<value>${person2.name}</value>
</property>
<property name="password">
<value>${person2.password}</value>
</property>
</bean>
</beans>
Person類:
public class Person{
private String name;
private String id;
private String password;
public String toString(){
return "Person id="+id+" name="+name+" password="+password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static void main(String[] args){
ApplicationContext appContext = new ClassPathXmlApplicationContext("bean.xml");
Person person1=(Person)appContext.getBean("person1");
System.out.println(person1);
Person person2=(Person)appContext.getBean("person2");
System.out.println(person2);
}
}
控制臺輸出:
Person id=001 name=Andy password=123456
Person id=002 name=Bill password=111111