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

I have a color.roperties file as

rose = red
lily = white
jasmine = pink

I need to get the value for the color as

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

where we get the color value at runtime. How to do it in java Spring. I need to get one value (from 50 values ​​defined in the properties file) at runtime based on user input. If I can't use @Value, could you tell me other ways to handle this?

+3
source share
3 answers

There is no way to do what you describe with @Value, but you can do it, which is very important:

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

PropertySource, Spring , flower, @Value .

Properties Map. , , , .

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

...

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

...

appProperties.getProperty(flower);
+2

@ike_love , , , , ? , , , Spring. , Spring, Spring, , PropertyPlaceholderConfigurer, , :

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:app.properties</value>
            </list>
        </property>
</bean>
0

All Articles