如何在Spring Boot应用中动态读取application.properties所有键值对
Spring Boot 动态读取所有application.properties键值对
你的需求完全可行,现有代码的问题在于逻辑错误:spring.config.name对应的是配置文件的名称(默认值为application),而非配置文件里的所有键名,所以你的代码只会尝试读取application这个键的值,自然得不到所有配置项。
以下是两种可行的实现方案:
方案一:通过Spring Environment收集所有配置
这种方式会获取Spring环境中加载的所有配置(包括application.properties、系统属性、环境变量等),如果只想保留application.properties的内容,可以通过PropertySource的名称过滤。
@Autowired private Environment environment; @GetMapping("/all-properties") public Map<String, String> getAllProperties() { Map<String, String> allProperties = new HashMap<>(); if (environment instanceof ConfigurableEnvironment configurableEnv) { for (PropertySource<?> propertySource : configurableEnv.getPropertySources()) { // 仅处理可枚举的属性源,筛选出application.properties相关的配置 if (propertySource instanceof EnumerablePropertySource<?> enumerableSource && propertySource.getName().contains("applicationConfig")) { for (String key : enumerableSource.getPropertyNames()) { Object value = environment.getProperty(key); allProperties.put(key, value != null ? value.toString() : "null"); } } } } return allProperties; }
方案二:直接读取application.properties文件
这种方式仅读取指定的配置文件,不会包含其他配置源的内容,适合只需要当前文件配置的场景。
@GetMapping("/app-properties") public Map<String, String> getApplicationProperties() throws IOException { Map<String, String> propertiesMap = new HashMap<>(); Properties properties = new Properties(); // 读取classpath下的application.properties文件 try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties")) { if (inputStream != null) { properties.load(inputStream); for (String key : properties.stringPropertyNames()) { propertiesMap.put(key, properties.getProperty(key)); } } } return propertiesMap; }
注意事项
- 如果采用方案一,可根据
propertySource.getName()的具体值调整过滤规则,避免返回系统变量、环境变量等无关配置。 - 生产环境中如果存在敏感配置(如密码、密钥),返回前需做脱敏处理,禁止直接暴露敏感信息。
内容的提问来源于stack exchange,提问作者OpenStack
相关产品推荐
相关产品推荐

