在spring的配置文件ApplicationContext.xml中加入.
<!-- 加载所有的properties文件,方便类中用spring注解方式获取 -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"><property name="locations">
<list>
<value>classpath:/properties/*.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:properties/jdbc.properties" />
<property name="properties" ref="configProperties" />
</bean>
需要用的类里面如下声明:
private String name;
public String getName() {
return name;
}
@Value("#{configProperties[name]}")
public void setName(String name) {
this.name = name;
}
意思就是读取*.properties文件中key为name的值,如果有多个properties文件。默认会合并,所以不需要关注是哪个properties中的key,如果多个properties中有重名的key,默认后面的会覆盖前面的。