gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:20:54 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com