java - 如何在 Spring Boot 中根据局部变量的值读取外部属性?

标签 java spring spring-boot spring-el

假设我的 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;
}

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

谢谢。

最佳答案

有多种方法可以实现这一点

如果你的属性不是由 spring 管理的

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

如果是用spring管理

1.) 你可以在 application.properies 中定义一个映射,可以在你的代码中注入(inject)映射读取你想要的任何属性

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

@Autowired 
private Environment environment;

public String getUrl(String year) {

    String url = "url." + year ;

    String value =environment.getProperty(url);

    return url;
}

关于java - 如何在 Spring Boot 中根据局部变量的值读取外部属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58637191/

相关文章:

database - Spring Boot 中是否有任何方法可以在不复制存储库的情况下将相同的数据提交到两个不同的数据源?

spring - 使用 Spring Boots application.properties 优化 JDBC 获取大小

java - nCipher 使用 KeySafe 在 java 中生成 AES key

java - 应用程序停止是因为按下了按钮?

java - 计算 sin(x) w/oMath 并仅在 java 中使用循环

java - 使用 Java 映射访问模式在 Mongo 中进行不同查询

java - Maven 依赖项到底是什么?

C# 相当于 Java 中的向命令参数添加关联数组

java - Apache Tomcat 重新启动。无法加载 com.mysql.jdbc.SQLError

java - 在 Spring 中的存储过程中传递参数