【问题标题】:Reading valued from properties file at Runtime在运行时从属性文件中读取值
【发布时间】:2011-08-05 15:16:57
【问题描述】:

我想根据属性文件的请求获取特定的值。如何做到这一点?

我有以下 spring 配置。我想根据请求设置 Exprops 的值并从属性文件中获取相应的值

<bean id="Prop" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>classpath:ErrorMessage.properties</value>
    </property>
</bean>

<bean id="PropertiesBean" class="com.util.PropertiesUtil">
    <property name="Exprops" value="${EXampleExceptiion}"></property>
</bean>

【问题讨论】:

  • PropertyPlaceholderConfigurer 仅用于配置您的应用程序,它是静态的,不打算由您的应用程序调用。
  • 我猜你必须自己实现这个。据我所知,Spring 对此没有具体的支持。
  • 感谢@Ralph,@Benjamin..任何人都可以为我提供从 PropertyPlaceholderConfigurer 读取的文件可用于在运行时设置值的实现

标签: spring properties


【解决方案1】:
<util:properties id="" location="location of prop file" />

这会返回 java.util.Properties 对象

【讨论】:

    【解决方案2】:

    所有人都使用以下程序以编程方式执行此操作

    XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    cfg.setLocation(new FileSystemResource("jdbc.properties"));
    cfg.postProcessBeanFactory(factory);
    

    【讨论】:

      【解决方案3】:

      使用PropertiesFactoryBean 将Properties 注入一个Bean。

      <bean id="myPropertiesBean"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:ErrorMessage.properties"/>
      </bean>
      

      这提供了一个Properties Object/Bean,可以在任何 Bean (&lt;property name="x" ref="myPropertiesBean"/&gt;) 中以名称 myPropertiesBean 注入。

      此外,Spring 提供了 util 命名空间(从 Spring 2.5 开始): 在那里您可以将 PropertyFactoryBean 定义写得更短一些:

      <util:properties id="myPropertiesBean"
       location="classpath:ErrorMessage.properties"/>
      

      @见Spring Reference Chapter C.2.2.3.

      【讨论】:

      • 谢谢@Ralph,这看起来更好
      • 我们可以在同一个 PropertiesFactoryBean 中编写多个属性,这些属性将被不同的 Spring beans 使用
      • @Vish:PropertiesFactoryBean 提供 java.util.Properties - 这是多个属性! (或者你的意思是,多个属性文件)。是的,您可以在不同的 bean 中使用它们(每个都将获得一个 java.util.Properties 实例,但具有相同的键/值)
      • 如果您的值是其他变量,则自动装配不会解析值。
      猜你喜欢
      • 2020-11-19
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 2012-03-04
      • 1970-01-01
      相关资源
      最近更新 更多