首页 > 解决方案 > 在单例类中读取 application.properties 一次

问题描述

我有一个单例配置类,我想在其中存储我们的 Web 应用程序的所有属性。

我们如何在不使用注释的情况下像任何其他属性文件一样读取 application.properies 文件?

application.properies 即 /application.properies 的完全限定文件名是什么?

我们只想读取 application.properties 一次。

标签: spring-boot

解决方案


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());
            }
        }
    }
}

推荐阅读