Get the values from the properties file at runtime based on the input - java Spring

15,743

Solution 1

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

Solution 2

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);
Share:
15,743
pinky
Author by

pinky

Updated on July 22, 2022

Comments

  • pinky
    pinky almost 2 years

    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?