0

I am using Java 8 on spring framework. I have a properties file which has "=" separated values in it. I am trying to load the values of the properties file into a Property directly using spring annotation. For example : my Application.properites has:

cat=250
dog=560
lama=1000
donkey=650

And I have declared this properties file in my context.xml as :

<util:properties id="app_props"
                 location="classpath*:/application.properties" />

Now in my main class I am trying to load all of the values in Application.properites into

private Properties properties;

So that properties.getProperty("cat") will return "250"

Not sure how to do it. May I get any help on that?

VictorGram
  • 2,521
  • 7
  • 48
  • 82
  • Is this a new project or an update to a legacy one? – chrylis -cautiouslyoptimistic- Oct 10 '18 at 04:38
  • 1
    Have you tried annotating `properties` with `@Resource(name="app_props")`? The `util:properties` is not quite the correct way to initialize/load your "properties"; I would recommend you to look into `context:property-placeholder`, and then use `Environment` or `@Value`. – x80486 Oct 10 '18 at 04:40

1 Answers1

0

Register your properties file as follows

XML Config

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-4.2.xsd">

      <context:property-placeholder location="classpath:foo.properties" />

</beans> 

Java Config

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
    //...
}

Using your properties as follows

@Value( "${jdbc.url}" )
private String jdbcUrl;

You can find a complete working solution in my GitHub repository

https://github.com/mirmdasif/springmvc/tree/master/springproperties

mirmdasif
  • 6,014
  • 2
  • 22
  • 28
  • 1
    I ended up using spring boot. Similar way described above. Other good examples of similar issues: 1> https://www.boraji.com/spring-boot-configurationproperties-example , 2> https://www.baeldung.com/configuration-properties-in-spring-boot , 3> https://stackoverflow.com/questions/9737812/properties-file-with-a-list-as-the-value-for-an-individual-key – VictorGram Oct 10 '18 at 17:20