2

In my Spring MVC application, I want to read ALL key/values from a specify properties file. I am including the properties file to my java class by

@PropertySource("classpath:user-form-validation-configuration.properties")

and can read a one key at a time

@Autowired
Environment env;

and env.getProperty("userIdEmail")

Please help me how to get all key/value as a map

Thanks Manu

Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
Manu
  • 1,243
  • 5
  • 17
  • 43

1 Answers1

4

One way to achieve the same is Spring: access all Environment properties as a Map or Properties object and secondly is:

<bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:user-form-validation-configuration.properties"/>
</bean>

For, Annotation based:

@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource(
                "user-form-validation-configuration.properties"));
        return bean;
}

Then you can pick them up in your application with:

@Resource(name = "myProperties")
private Map<String, String> myProperties;
Community
  • 1
  • 1
Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
  • Thanks lot Arpit,Second option is more clean and clear.But can I avoid the bean creation in xml file.direct can include the properties file in my Java class, or annotated class to load the properties file. – Manu Jun 01 '15 at 01:20
  • yes got it, in jjava I am able to configure .@Bean(name="myProperties") public static PropertiesFactoryBean mapper() { PropertiesFactoryBean bean = new PropertiesFactoryBean(); bean.setLocation(new ClassPathResource("user-form-validation-configuration.properties")); return bean; } – Manu Jun 01 '15 at 01:51
  • 1
    Updated the post, for annotation based. – Arpit Aggarwal Jun 01 '15 at 08:22
  • @Manu: accept the answer, if it works - http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Arpit Aggarwal Dec 15 '15 at 10:28
  • @Manu you should accept useful answers, that's the way this site works – JimHawkins Jan 20 '17 at 10:44