10

I have my colour.roperties file as

rose = red
lily = white
jasmine = pink

I need to get the value for colour as

String flower = runTimeFlower;
@Value("${flower}) String colour;

where flower value we will get at runtime. How can I do this in java Spring. I need to get a single value (from among 50 values defined in the properties file )at runtime based on the user input. If i cannot use @Value , Could you tell me other ways to handle this please?

pinky
  • 129
  • 1
  • 1
  • 5

3 Answers3

22

There is no way to do what you are describing using @Value, but you can do this, which is the same thing pretty much:

package com.acme.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class Example {
    private @Autowired Environment environment;

    public String getFlowerColor(String runTimeFlower) {
        return environment.resolvePlaceholders("${" + runTimeFlower + "}");
    }
}
SergeyB
  • 9,478
  • 4
  • 33
  • 47
  • Upvoting as a valid option, though I tried to avoid such a tight binding to Spring in my answer. I guess @user3147038 still needs to learn to upvote and accept answers. :) – Emerson Farrugia Feb 07 '14 at 13:31
4

The PropertySources which Spring reads from won't know the value of the flower variable, so @Value won't work.

Inject a Properties object or a Map. Then just look up the colour using the property name or key, respectively, e.g.

<util:properties id="appProperties" location="classpath:app.properties" />

...

@Autowired 
@Qualifier("appProperties")
private Properties appProperties;

...

appProperties.getProperty(flower);
Emerson Farrugia
  • 11,153
  • 5
  • 43
  • 51
0

What @ike_love says it correct, but why don't you just load the properties in memory on app start and then you can resolve your flower taking value from a map? In my mind you don't need to delegate every simple thing like this to Spring. Anyway I don't know your Spring config, but in order Spring to be able to load the properties you need to define a PropertyPlaceholderConfigurer to tell where are the property files:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:app.properties</value>
            </list>
        </property>
</bean>
Boyan
  • 589
  • 5
  • 19