Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 453
pinky Avatar asked Feb 06 '14 17:02

pinky


People also ask

How do I fetch values from application properties in spring boot?

You can use @Value("${property-name}") from the application. properties if your class is annotated with @Configuration or @Component . You can make use of static method to get the value of the key passed as the parameter. Save this answer.

How do you get all values from properties file in java?

Get All Key Values from Properties File Get All Key Values from Properties File in java using the Properties class Available in java. util Package. The Properties class extends the Hashtable class. From Hashtable, Properties class inherits the Method KeySet() which Returns a Set view of the keys Contained in this Map.


2 Answers

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 + "}");
    }
}
like image 162
SergeyB Avatar answered Oct 26 '22 14:10

SergeyB


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);
like image 44
Emerson Farrugia Avatar answered Oct 26 '22 15:10

Emerson Farrugia