Search code examples
javaspringspring-bootspring-el

How to read external properties based on value of local variable in Spring Boot?


let say I have the following properties in my application.properties

url.2019=http://example.com/2019
url.2020=http://example.com/2020

And I have this method,

public String getUrl(String year) {

    String url;

    // here I want to read the property value based on the value of year
    // if year is "2019", I want to get the value of ${url.2019}
    // if year is "2020", I want to get the value of ${url.2020}
    // something like #{url.#{year}} ??

    return url;
}

What is the best way to achieve this?

Thank you.


Solution

  • There could be multiple ways to achieve this

    If your properties are not managed by spring

    https://www.baeldung.com/inject-properties-value-non-spring-class

    If it is managed by spring

    1.) you can define a map in application.properies, can inject the map in your code read whichever property you want

    2) you can inject environment variable and read property on demand

    @Autowired 
    private Environment environment;
    
    public String getUrl(String year) {
    
        String url = "url." + year ;
    
        String value =environment.getProperty(url);
    
        return url;
    }