0

question is related to Spring. I have application.properties file in my project. I want these values to be used in my service class. Can i get these properties values as a bean in my service class?

class MyServiceClass{
    @Autowired
    Properties myproperty;

    // ....
}

i want to be able to use myproperty. What config changes should be made to wire the application.properties with my service class?

kryger
  • 12,906
  • 8
  • 44
  • 65
Sathish
  • 11
  • 4
  • possible duplicate of [reading a dynamic property list into a spring managed bean](http://stackoverflow.com/questions/5274362/reading-a-dynamic-property-list-into-a-spring-managed-bean) – fracz Mar 20 '15 at 10:26
  • That is not a duplicate of this one. But there should be one, seems like a common thing to want to do. +1 since I cannot find a duplicate. – Thilo Mar 20 '15 at 10:31

2 Answers2

0

You can inject them into your beans:

 @Value("${name}")
 private String someConfiguration;
Thilo
  • 257,207
  • 101
  • 511
  • 656
0

Not sure if I fully understand the question. I guess you want to access both the key and values from your props file? If so, perhaps this will help:

<bean id="mapProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="ignoreResourceNotFound" value="true"/>
    <property name="fileEncoding" value="UTF-8"/>
    <property name="locations">
        <list>
            <value>classpath:application.properties</value>
        </list>
    </property>
</bean>

<bean id="myMap" class="com.google.common.collect.ImmutableMap" factory-method="copyOf">
    <constructor-arg ref="mapProperties"/>
</bean>

Now you can access myMap in your beans as you would normally:

@Autowired
private ImmutableMap<String, String> myMap;

This example uses a guava ImmutableMap, but you can probably use HashMap or whatever.

Somaiah Kumbera
  • 7,063
  • 4
  • 43
  • 44