Spring Boot读取YAML配置到Map抛出异常问题求助
Spring Boot读取YAML自定义属性到Map异常排查
问题背景
在Spring Boot项目中尝试从YAML文件读取自定义属性并映射到Map<String, List<Content>>结构时,运行时抛出异常,无法正确加载数据。
核心问题及解决方案
1. @PropertySource默认不支持YAML格式
Spring原生的@PropertySource注解仅支持.properties和.xml格式配置文件,无法直接加载YAML文件。这会导致你的utility-customization.yaml未被加载,section属性始终为null,调用configurations.getSection()时触发空指针异常。
解决方法:
- 移除
@PropertySource注解,将YAML文件纳入Spring Boot自动加载机制:- 若使用多环境配置,可将文件命名为
application-custom.yaml,并在主application.yaml中通过spring.profiles.active=custom激活; - 或保持原文件名,在项目启动类上添加
@ConfigurationPropertiesScan注解,让Spring Boot扫描并加载自定义配置类。
- 若使用多环境配置,可将文件命名为
2. YAML结构与实体类不匹配
你的YAML配置中每个Content对象外层多了一层content:,但Content类直接包含displayName和link属性,属性层级不匹配会导致映射失败,即使文件被加载,List<Content>也会为空。
修改后的YAML结构:
utility: customization: section: headerSection: - displayName: "Gerrit" link: "#" - displayName: "Gerrit1" link: "#"
3. 确保@ConfigurationProperties生效
在项目启动类上添加@EnableConfigurationProperties(SectionConfigurations.class),显式启用配置属性绑定;同时可添加依赖获得IDE提示支持:
Maven依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
4. 空指针异常防护
在代码中增加空判断,避免直接调用get()方法触发空指针:
try{ Map<String, List<Content>> sectionMap = configurations.getSection(); if(sectionMap == null){ throw new CustomizeException("Customize content section not found"); } List<Content> data = sectionMap.get("headerSection"); }catch (Exception e){ throw new CustomizeException("Customize content from file not loaded", e); }
最终修正后的关键代码
SectionConfigurations.java
package com.tool.osoutilityapp.customconfig; import com.tool.osoutilityapp.customconfig.model.Content; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import java.util.List; import java.util.Map; @Configuration @ConfigurationProperties(prefix = "utility.customization") public class SectionConfigurations { private Map<String, List<Content>> section; public Map<String, List<Content>> getSection() { return section; } public void setSection(Map<String, List<Content>> section) { this.section = section; } }
启动类示例
@SpringBootApplication @EnableConfigurationProperties(SectionConfigurations.class) public class OsoUtilityAppApplication { public static void main(String[] args) { SpringApplication.run(OsoUtilityAppApplication.class, args); } }
内容的提问来源于stack exchange,提问作者Dante1501
相关产品推荐
相关产品推荐

