读取error.yml存入指定Map时返回null,寻求技术帮助
问题描述
需要读取error.yml文件中的数据,存入指定结构的Map中,但使用配置类存储时结果为null,请求解决。
配置类代码
@Configuration @PropertySource(value = "classpath:error.yml ", factory = YamlPropertySourceFactory.class) @EnableConfigurationProperties @ConfigurationProperties(prefix = "errorcodes") @Getter @Slf4j @ConstructorBinding public class ErrorService { private Map<String, ApiError> errors = new HashMap<>(); // 省略其他代码 }
error.yml内容
errorcodes: errors: ERROR_1: code: 1 message: 内部服务器错误
解决方案
以下是导致Map为null的常见原因及修复方法:
修复
@ConstructorBinding的使用问题@ConstructorBinding要求通过构造函数注入属性,当前代码直接初始化errors且无对应构造函数,会导致注入失败。
要么添加带errors参数的构造函数:@Configuration @PropertySource(value = "classpath:error.yml", factory = YamlPropertySourceFactory.class) @EnableConfigurationProperties @ConfigurationProperties(prefix = "errorcodes") @Getter @Slf4j @ConstructorBinding public class ErrorService { private final Map<String, ApiError> errors; public ErrorService(Map<String, ApiError> errors) { this.errors = errors; } // 省略其他代码 }要么移除
@ConstructorBinding,并为errors添加setter方法(或添加@Setter注解):@Configuration @PropertySource(value = "classpath:error.yml", factory = YamlPropertySourceFactory.class) @EnableConfigurationProperties @ConfigurationProperties(prefix = "errorcodes") @Getter @Setter @Slf4j public class ErrorService { private Map<String, ApiError> errors = new HashMap<>(); // 省略其他代码 }确保
ApiError类配置正确ApiError需为普通Java类,包含code和message的getter方法(或使用@Data注解简化),否则Spring无法完成属性绑定:@Data public class ApiError { private Integer code; private String message; }检查
YamlPropertySourceFactory实现正确性
自定义的YAML加载工厂类需正确解析文件,确保实现如下:public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); Properties properties = factory.getObject(); return new PropertiesPropertySource(name != null ? name : resource.getResource().getFilename(), properties); } }校验YAML文件缩进格式
YAML对缩进敏感,确保层级缩进统一使用2个空格(禁止用tab):errorcodes: errors: ERROR_1: code: 1 message: 内部服务器错误确认配置类被Spring扫描
检查ErrorService所在包是否在Spring组件扫描范围内,可在主启动类添加@ComponentScan指定包路径,或确保@Configuration注解被Spring识别。
内容的提问来源于stack exchange,提问作者swanthri
相关产品推荐
相关产品推荐

