首页 > 解决方案 > 如何根据 Spring Boot 中的局部变量值读取外部属性?

问题描述

假设我的 application.properties 中有以下属性

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

而我有这个方法,

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;
}

实现这一目标的最佳方法是什么?

谢谢你。

标签: javaspringspring-bootspring-el

解决方案


可能有多种方法可以实现这一目标

如果您的房产不是由 spring 管理的

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

如果由spring管理

1.) 您可以在 application.properies 中定义地图,可以在代码中注入地图,读取您想要的任何属性

2)您可以按需注入环境变量和读取属性

@Autowired 
private Environment environment;

public String getUrl(String year) {

    String url = "url." + year ;

    String value =environment.getProperty(url);

    return url;
}

推荐阅读