第一种方法:
properties文件内容
dataSource.url="123"
dataSource.username="123"
dataSource.password="123"
dataSource.driverClassName="123"
在配置文件applicationContext.xml配置,如果是单个个properties文件<value>/config/configInfo.properties</value>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:/config/config.properties</value>
<value>classpath:/config/db.properties</value>
</list>
</property>
</bean>
在类中以成员变量的形式获取properties对应的值
@Value("${dataSource.url}")
private String url;
第二钟方法:
在xml文件获取对应属性,
<context:property-placeholder location="classpath:conn.properties"/>
context:property-placeholder改配置也是创建一个PropertyPlaceholderConfigurer的bean实例
默认spring只维护一个PropertyPlaceholderConfigurer的bean实例,加如下属性ignore-unresolvable="true"即可有多个
第一种方法不加<property name="ignoreUnresolvablePlaceholders" value="true" />也会与<context:property-placeholder?>冲突
<bean id="mtpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${dataSource.driverClassName}" />
<property name="url">
<value>${dataSource.url}</value>
</property>
<property name="username">
<value>${dataSource.username}</value>
</property>
<property name="password">
<value>${dataSource.password}</value>
</property>
<property name="initialSize" value="20" />
<property name="maxActive" value="500" />
<property name="maxIdle" value="20" />
<property name="maxWait" value="500" />
<property name="defaultAutoCommit" value="true" />
<!-- <property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="60" /> -->
<property name="testOnBorrow" value="true"/>
<property name="validationQuery" value="select 1 from dual"/>
</bean>
第一种和第二种配置和获取可以混用
第三种方法:
第一种方法在类中每用一次要声明一个局部变量,也可以通过重写processProperties()的方法获取
public class MyPropertyConfig extends PropertyPlaceholderConfigurer {
private Map<String, String> ctxPropertiesMap;
@Override
protected void processProperties(ConfigurableListableBeanFactory factory, Properties props) throws BeansException {
super.processProperties(factory, props);
ctxPropertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
ctxPropertiesMap.put(keyStr, value);
}
}
public String getVal(String name) {
return ctxPropertiesMap.get(name);
}
}
xml配置文件中
<bean id="myPropertyConfig" class="xxx.MyPropertyConfig">
<property name="ignoreUnresolvablePlaceholders" value="true" /> <property name="locations"> <list> <value>classpath:/config/config.properties</value> <value>classpath:/config/db.properties</value> </list> </property> </bean>
在类中如此写即可调用对应属性
@Resource
private MyPropertyConfig mtpPropertyConfig;
@Test
public void test(){
myPropertyConfig.getVal("dataSource.url")
}