在运行时从属性文件中读取值

问题描述 投票:1回答:3

我希望根据属性file.how的请求获取特定值来做到这一点?

我有以下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>
spring properties
3个回答
10
投票

使用PropertiesFactoryBean将Bean中的Properties注入。

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

这提供了一个Properties对象/ Bean,可以在任何Bean(myPropertiesBean)中以名称<property name="x" ref="myPropertiesBean"/>注入。

另外Spring提供了util命名空间(自Spring 2.5开始):你可以将PropertyFactoryBean定义写得更短一些:

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

@see Spring Reference Chapter C.2.2.3.


1
投票

以编程方式执行此操作均使用以下内容

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

0
投票
<util:properties id="" location="location of prop file" />

这返回java.util.Properties对象

© www.soinside.com 2019 - 2024. All rights reserved.