java - 如何根据 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;
}
实现这一目标的最佳方法是什么?
谢谢你。
解决方案
可能有多种方法可以实现这一目标
如果您的房产不是由 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;
}
推荐阅读
- java - 如何为类中的 2 个泛型类型重载函数
- c++ - 直接合成,IDCompositionGaussianBlurEffect 抛出访问冲突异常
- c++ - c++二进制动态编译但不是静态编译时的glibc错误
- curl - 如何将 os.execute 存储为变量
- python - 有什么方法可以将变量传递给 django 元类?
- python - 从 haarcascade 中提取眼睛
- airflow - 气流调度程序在除周二外的所有日子里运行 DAG 不起作用
- java - 即使在导入库并安装所有组件之后,Eclipse 中的 WindowBuilder 也无法工作
- c# - 构建并上传到服务器以运行后未找到 dll
- mysql - MYSQL正确排序带有中间句号的列