簡體   English   中英

Spring MVC 2.5:如何加載屬性文件

[英]Spring MVC 2.5: how to load properties file

我需要加載許多屬性文件,這些文件位於資源文件夾中。

我有一個名為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");

我怎樣才能做到這一點?

謝謝

您需要在上下文文件中定義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批注,則需要在上下文文件中放入<context:annotation-config />元素。

您需要在xml文件中定義messagesource bean。

試試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM