分散配置
在应用上下文中,使用PropertyPlaceholderConfigurer从外部属性文件装载的配置信息:
应用上下文中从当个外部外部属性文件装载配置信息:
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="cn/csdn/service/jdbc.properties"/> </bean>
其中,location属性允许使用单个配置文件,可试用其locations属性设置配置文件列表:
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>cn/csdn/service/jdbc.properties</value> <value>cn/csdn/service/security.properties</value> <value>cn/csdn/service/application.properties</value> </list> </property> </bean>
这样,就可用占位符变量代替Bean配置文件中硬编码配置中。语法上,占位符变量采用${variacle}的形式,如下:
ConnServiceImpl.java
package cn.csdn.service;
public class ConnServiceImpl {
private String driverClass;
private String url;
private String user;
private String password;
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
public void setUrl(String url) {
this.url = url;
}
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClass() {
return driverClass;
}
public String getUrl() {
return url;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
}
<bean id="connServiceImpl" class="cn.csdn.service.ConnServiceImpl" scope="singleton"> <property name="driverClass"> <value>${jdbc:driverClass}</value> </property> <property name="url"> <value>${jdbc:url}</value> </property> <property name="user"> <value>${jdbc:user}</value> </property> <property name="password"> <value>${jdbc:password}</value> </property> </bean>
jdbc.properties
jdbc\:driverClass=com.mysql.jdbc.Driver
jdbc\:url=jdbc\:mysql\://localhost\:3306/db
jdbc\:user=z_xiaofei168
jdbc\:password=root