Spring读取properties:PropertiesFactoryBean和PropertyPlaceholderConfigurer

更多参考: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>
复制代码

 

  1.  <!-- <util:properties/> 标签只能加载一个文件,当多个属性文件需要被加载的时候,可以使用多个该标签 -->  
  2.  <util:properties id="remoteSettings" location="file:/opt/demo/config/demo-remote.properties" />   
  3.    
  4.  <!-- <util:properties/> 标签的实现类是PropertiesFactoryBean,  
  5.  直接使用该类的bean配置,设置其locations属性可以达到一个和上面一样加载多个配置文件的目的 -->  
  6.  <bean id="settings"   
  7.    class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  8.    <property name="locations">  
  9.   <list>  
  10.     <value>file:/opt/rms/config/rms-mq.properties</value>  
  11.     <value>file:/opt/rms/config/rms-env.properties</value>  
  12.   </list>  
  13.    </property>  
  14.  </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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值