Spring是否将所有属性存入同一哈希表?如何遍历所有属性?
Spring 属性存储与全属性获取方案
问题1:Spring是否会将所有属性存入同一个hashmap/list?
Spring不会将所有属性直接存入单一的HashMap或List,而是通过**PropertySources集合管理多个属性源(比如@PropertySource加载的配置文件、系统属性、环境变量等)。但对于重复的属性键,Spring遵循后加载属性源覆盖先加载**的规则,最终对外提供统一的属性访问视图,看起来像是存储在同一个逻辑容器中,但底层是多属性源的组合结构。
以你的示例为例:
file1.properties先加载,其中prop1.fill=greenfile2.properties后加载,其中prop1.fill=ORANGE
最终Spring生效的prop1.fill值为ORANGE。
问题2:如何获取Spring管理的所有属性列表?
可以通过Spring的Environment接口实现全属性遍历,具体实现如下:
实现步骤
- 注入
ConfigurableEnvironment(Environment的子接口,支持直接访问属性源) - 遍历所有属性源,提取每个源中的键值对
代码示例
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; import javax.annotation.PostConstruct; import java.util.Map; @Configuration public class PropertyIterator { @Autowired private ConfigurableEnvironment env; @PostConstruct public void iterateAllProperties() { // 遍历所有属性源 for (PropertySource<?> propertySource : env.getPropertySources()) { // 处理@PropertySource加载的配置文件这类基于Map的属性源 if (propertySource instanceof MapPropertySource) { Map<String, Object> properties = ((MapPropertySource) propertySource).getSource(); // 迭代输出所有属性键值对 for (Map.Entry<String, Object> entry : properties.entrySet()) { System.out.printf("属性键:%s,属性值:%s%n", entry.getKey(), entry.getValue()); } } // 若需要包含系统属性、环境变量,可添加对SystemPropertiesPropertySource等类型的判断处理 } } }
示例输出
结合你的配置文件,运行后会输出:
属性键:prop1.color,属性值:red 属性键:prop1.fill,属性值:ORANGE 属性键:prop2.color,属性值:purple
注意事项
- 不同类型的属性源需单独处理:比如系统属性对应
SystemPropertiesPropertySource,环境变量对应SystemEnvironmentPropertySource,按需添加类型判断即可遍历这些属性 - 遍历得到的是最终生效的属性值(后加载源覆盖先加载源的重复属性)
- Spring Boot环境下逻辑完全一致,直接通过
Environment即可操作
内容的提问来源于stack exchange,提问作者PatS
相关产品推荐
相关产品推荐

