Spring读取自定义YAML文件Map时遇NumberFormatException问题求助
解决Spring读取自定义YAML文件时的NumberFormatException问题
问题原因
@PropertySource默认不支持解析YAML格式文件,导致YAML中的类型标签(如!!str)无法生效- 配置的数值超出Java
Integer范围,Spring默认按Integer解析时触发NumberFormatException
解决方案
方案1:改用Long类型Map(推荐,适配大数值)
步骤1:自定义YAML属性源工厂
实现PropertySourceFactory让@PropertySource支持YAML:
import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.boot.env.YamlPropertySourceLoader; import java.io.IOException; public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()).get(0); } }
步骤2:修改配置类
将Map类型改为<String, Long>,并指定自定义工厂:
@Data @Configuration @PropertySource(value = "classpath:/id.yml", factory = YamlPropertySourceFactory.class) public class ChatIdProperties { @Value("#{${id}}") Map<String, Long> id; }
方案2:强制解析为String类型
步骤1:修改YAML配置
用引号包裹数值或使用!!str标签标记为字符串:
# 方式1:引号包裹 id: id1: "-1001978483459" id2: "-1001978483457" # 方式2:使用!!str标签 id: id1: !!str -1001978483459 id2: !!str -1001978483457
步骤2:配置类指定YAML工厂
同样需要添加自定义工厂支持YAML解析,保持Map为<String, String>:
@Data @Configuration @PropertySource(value = "classpath:/id.yml", factory = YamlPropertySourceFactory.class) public class ChatIdProperties { @Value("#{${id}}") Map<String, String> id; }
方案3:使用@ConfigurationProperties绑定(更优雅)
替代@Value,直接通过前缀绑定属性,无需手动解析Map:
@Data @Configuration @PropertySource(value = "classpath:/id.yml", factory = YamlPropertySourceFactory.class) @ConfigurationProperties(prefix = "id") public class ChatIdProperties { private Map<String, String> id; }
此方式下,YAML配置用方案2中的任意一种即可正确绑定为String类型。
内容的提问来源于stack exchange,提问作者BANTYC
相关产品推荐
相关产品推荐

