spring-boot - 在单例类中读取 application.properties 一次
问题描述
我有一个单例配置类,我想在其中存储我们的 Web 应用程序的所有属性。
我们如何在不使用注释的情况下像任何其他属性文件一样读取 application.properies 文件?
application.properies 即 /application.properies 的完全限定文件名是什么?
我们只想读取 application.properties 一次。
解决方案
Spring boot 已经读取了存储在其中的所有属性application.properties
以及更多内容,请阅读Externalized Configuration文档。
如果您想映射一个名为的属性server.port
,您可以使用@Value("${server.port}") Integer port
.
如果要访问 Spring Boot 加载的所有属性,可以使用该Environment
对象并访问所有加载PropertySources
并从每个属性源检索所有值。
在这个答案中显示了如何。但是,为了避免丢失加载属性的优先顺序,您必须反转属性源列表。在这里您可以找到加载所有属性而不丢失弹簧优先顺序的代码:
@Configuration
public class AppConfiguration {
@Autowired
Environment env;
public void loadProperties() {
Map<String, Object> map = new HashMap();
for (Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator().reverse(); it.hasNext(); ) {
PropertySource propertySource = (PropertySource) it.next();
if (propertySource instanceof MapPropertySource) {
map.putAll(((MapPropertySource) propertySource).getSource());
}
}
}
}
推荐阅读
- c - 指向结构的指针作为函数的参数有什么用?
- python - Pandas:基于另一个系列设置一个系列中的值,其中一些索引是共同的,有些不是
- java - 任何集合 O(1) indexOf 时间复杂度?
- python - 我如何计算系列的总和 s = 1=(1! + 2! +3!. . + n!) % 1000000007 其中 n 的范围从 0 到 10^6
- amazon-web-services - 这些设置对 S3 中的阻止公共访问设置意味着什么?
- azure - Azure DevOps 托管代理无法拉取 windows:2004
- java - 仅在 java 中返回指定字段和 _id 字段
- python - 如何在对 Pandas 数据框重新采样期间创建额外的列?
- python - Python 使用脚本更改命令行参数
- android - “您必须在 2020 年 11 月 1 日之前在您的应用中实施帐户保留和恢复。” - 此消息在 Google Play 控制台中的含义是什么?