更多参考:http://kingxss.iteye.com/blog/1880681
PropertiesFactoryBean 是PropertiesLoaderSupport 直接的实现类, 专门用来管理properties文件的工厂bean,默认是单例的,
而 PropertyPlaceholderConfigurer 是 解决 properties 文件占位符问题的,也实现了 PropertiesLoaderSupport 类。
在Java 代码里,一般是使用@Value注解来引用 properties 文件的属性。
使用 PropertyPlaceholderConfigurer 时, @Value表达式的用法是 @Value(value="${properties key}") ,
使用 PropertiesFactoryBean 时,我们还可以用@Value 读取 properties对象的值, @Value 用法 是 @Value(value="#{configProperties['properties key']}")
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:/config/jdbc.properties</value> <value>classpath:/config/base.properties</value> </list> </property> </bean> <!-- 属性文件读入 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="properties" ref="configProperties" /> </bean>
- <!-- <util:properties/> 标签只能加载一个文件,当多个属性文件需要被加载的时候,可以使用多个该标签 -->
- <util:properties id="remoteSettings" location="file:/opt/demo/config/demo-remote.properties" />
- <!-- <util:properties/> 标签的实现类是PropertiesFactoryBean,
- 直接使用该类的bean配置,设置其locations属性可以达到一个和上面一样加载多个配置文件的目的 -->
- <bean id="settings"
- class="org.springframework.beans.factory.config.PropertiesFactoryBean">
- <property name="locations">
- <list>
- <value>file:/opt/rms/config/rms-mq.properties</value>
- <value>file:/opt/rms/config/rms-env.properties</value>
- </list>
- </property>
- </bean>
spring 2.5之后,可以使用
<context:property-placeholder location="classpath:com/foo/jdbc.properties"/>
其本质是注册了一个PropertyPlaceholderConfigurer(3.1之前)或者是PropertySourcesPlaceholderConfigurer(3.1之后)
@Value(value="${profit.rate.csProfitRate}") double rate = 0.9; @Value(value="#{configProperties['profit.rate.csProfitRate']}") double rate2 = 0.9;