【问题标题】:Spring MVC 2.5: how to load properties fileSpring MVC 2.5:如何加载属性文件
【发布时间】:2012-07-23 17:27:19
【问题描述】:

我需要加载资源文件夹中的许多属性文件。

我有一个名为 abc_en.properties 的资源,其内容如下:
a = x
b = y
c = z

我需要在 Java 方法中使用属性 sing java.util.Properties:

  java.util.Properties reportProperties = new java.util.Properties();   
   ...
  String a = reportProperties.getProperty("a");

我该怎么做?

谢谢

【问题讨论】:

  • 我正在寻找最佳解决方案。我有一个名为 xyz_en.properties 的资源,我需要使用其中定义的属性,使用 java.util.Properties

标签: java spring-mvc


【解决方案1】:

您需要在上下文文件中定义 propertyConfigurer bean:

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:abc.properties</value>
            <value>classpath:efg.properties</value>
        </list>
    </property>
</bean>

编辑:

为了使用java.util.Properties,您需要在上下文文件中定义PropertiesFactoryBean bean:

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

然后你需要在你的类中定义一个 java.util.Properties 变量并将属性 bean 加载到其中:

public class MyClass {

     @Autowired
     private java.util.Properties properties;


     public void myMethod() {
         String a = properties.getProperty("a");
         String b = properties.getProperty("b");
         String c = properties.getProperty("c");
     }
}

还有其他方法可以将属性 bean 加载到您的类中,但如果您使用 @Autowired 注释,则需要将 &lt;context:annotation-config /&gt; 元素放入您的上下文文件中。

【讨论】:

  • 您可以将属性分配给类中的变量,就像您的属性文件中有my.application.variable=something一样,您可以定义一个spring bean,例如:&lt;bean class="my.class"&gt; &lt;property name="variable" value="${my.application.variable}"/&gt; &lt;/bean&gt;
  • 那么,每个 .properties 都需要一个 bean 吗?每个属性都有一个字段?
  • 谢谢,我正在尝试解决方案,但现在我遇到了另一个问题stackoverflow.com/questions/11653373/…
【解决方案2】:

您需要在 xml 文件中定义消息源 bean。

试试这个方法

<bean id="messageSource" name="applicationMessageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
      <list>
          <value>resources.abc.abc</value>
       </list>
    </property>
</bean>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2015-01-23
    • 2015-05-25
    • 2019-03-30
    • 2017-11-17
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多