美文网首页
spring 属性加载及获取

spring 属性加载及获取

作者: 骑忆 | 来源:发表于2017-11-24 11:54 被阅读0次

    一、属性文件加载

    方案1:通配符解决、逗号分隔

    使用通配符让spring一次性读取多个属性文件到一个PropertyPlaceholderConfigurerbean中
    <context:property-placeholder location="classpath:conf/.properties"/>

    或者使用
    <context:property-placeholder location="classpath*:conf/db.properties,conf/sys.properties"/>

    注意: 如果后一个文件中有和前面某一个文件中属性名是相同的,最终取的值是后加载的值

    方案2:一个PropertySourcesPlaceholderConfigurer中包含多个属性文件,和方案1原理相同

    <bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="locations">
         <list>
             <value>classpath:db.properties</value>
              <value>classpath:sys.properties</value>
          </list>
    </property>
    

    方案3:使用ignore-unresolvable

    如果一定要分开定义,则在每个PropertySourcesPlaceholderConfigurer配置中添加
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
    或者在每个context:property-placeholder中都加上ignore-unresolvable="true"

    因为在你使用@Value("${xx}")或在xml中使用${xx}获取属性时,Spring会在第一个读取到的属性文件中去找,如果没有就直接抛出异常,而不会继续去第二个属性文件中找。

    二、属性获取

    方案一:Bean中直接注入Properties配置文件中的值

     <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>  
    

    Client类中使用Annotation如下:

    import org.springframework.beans.factory.annotation.Value;  
    public 
    class Client() {
        @Value("#{remoteSettings['remote.ip']}")
        private String ip;  
        @Value("#{remoteSettings['remote.port']}")
        private String port;  
        @Value("#{remoteSettings['remote.serviceName']}")
        private String service;  
     }
    

    注意:被注入属性的那个类,如果被其他类作为对象引用(被调用)。这个被调用的类也必须选择注解的方式,注入到调用他的那个类中,不能用 new出来做对象,new出来的对象再注入其他bean就会发生属性获取不到的现象。所以要被调用的javabean,都需要@service,交给Spring去管理才可以,这样他就默认注入了。

    参考:http://blog.csdn.net/zheng963/article/details/46558739

    相关文章

      网友评论

          本文标题:spring 属性加载及获取

          本文链接:https://www.haomeiwen.com/subject/epbxbxtx.html