【问题标题】:How to get any property from .properties file without explicitly calling its getter如何在不显式调用其 getter 的情况下从 .properties 文件中获取任何属性
【发布时间】:2021-08-30 20:30:06
【问题描述】:

有没有办法在 .properties 文件中添加一个属性而不调用它的 getter。

所以我期待的是:

application.properties

name=user1
email=user@xyzdomain.com
contact=123-456-0789
header=val1,val2,val3
.
.
.

现在,我该如何编写这样的方法:

public String getKey(String key) {
    // any key passed, eg: name and I should get its value
    // Do I have to create a switch statement to see which key it is and using the //mapping of its corresponding getter method, call that getter. Is there a better way?
    ...
} 

所以,任何传递的键,例如:名称,我都应该得到它的值。我是否必须创建一个 switch 语句来查看它是哪个键并使用其相应 getter 方法的映射,调用该 getter。有没有更好的办法?

【问题讨论】:

  • 你尝试注入org.springframework.core.env.Environment吗?

标签: java spring-boot properties-file


【解决方案1】:

org.springframework.core.env.Environment 是一个接口,代表当前应用程序正在运行的环境(您的application.properties 也是如此)。

通过它的实例,您可以通过键访问为应用程序加载的任何属性值。

@Autowired
private Environment env;
....

public String getKey(String key) {
    .....  
    return env.getProperty(key);
}

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多