Javi Pedrera
Javi Pedrera

Reputation: 2095

Spring MVC 2.5: how to load properties file

I need to load many properties files, which are in the resources folder.

I have a resource called abc_en.properties with the content below:
a = x
b = y
c = z

and I need to use the properties sing java.util.Properties in a Java Method:

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

How can I do this?

Thanks

Upvotes: 2

Views: 7778

Answers (2)

AxxA Osiris
AxxA Osiris

Reputation: 1209

You need to define the propertyConfigurer bean in your context file:

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

EDIT:

In order to use java.util.Properties you need to define the PropertiesFactoryBean bean in your context file :

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

Then in your class you need to define a java.util.Properties varible and load the properties bean into it :

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");
     }
}

There are other ways to load the properties bean into you class, but if you use the @Autowired annotation, you need to put the <context:annotation-config /> element in you context file.

Upvotes: 4

kartheek
kartheek

Reputation: 320

You need to define the messagesource bean in your xml file.

Try this way

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

Upvotes: 0

Related Questions