如何用Jackson将Properties对象转换为自定义对象?
一、使用Jackson实现转换
如果已经持有Properties对象,可以通过Jackson将其转换为目标Artist Record,步骤如下:
将Properties转换为Map
先把Properties键值对转成HashMap,Jackson对Map的映射支持更直接:Map<String, Object> propsMap = new HashMap<>(); properties.forEach((key, value) -> propsMap.put(key.toString(), value));用Jackson ObjectMapper完成映射
Jackson原生支持Java Record的序列化/反序列化,直接调用convertValue方法即可将点分隔的键映射为嵌套对象结构:ObjectMapper objectMapper = new ObjectMapper(); // 可选:开启大小写不敏感匹配,适配不同格式的配置键 objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); Artist artist = objectMapper.convertValue(propsMap, Artist.class);原理:Jackson会自动解析
artist.elvis.name这类点分隔键,将其映射到Artist内部嵌套的ElvisRecord对应的字段上,无需额外配置。
二、更优的Spring Boot原生方案
在Spring Boot场景下,手动读取YAML转Properties再转对象的方式并非最优解,推荐使用Spring Boot配置绑定功能,直接将配置文件内容绑定到自定义对象:
配置自定义Record并添加注解
调整Artist的访问权限(Spring需要能访问类及内部Record),并添加@ConfigurationProperties指定配置前缀:@ConfigurationProperties(prefix = "artist") public record Artist(Elvis elvis) { public record Elvis(String name, String message) { } }启用配置绑定
在Spring Boot主类或任何配置类上添加@EnableConfigurationProperties注解,或者直接给Artist添加@Component(需确保类在组件扫描路径下):@SpringBootApplication @EnableConfigurationProperties(Artist.class) public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }直接注入使用
现在可以在任何Spring管理的Bean中直接注入Artist对象:@Service public class ArtistService { private final Artist artist; public ArtistService(Artist artist) { this.artist = artist; } public void printArtistInfo() { System.out.println("Name: " + artist.elvis().name()); System.out.println("Message: " + artist.elvis().message()); } }优势:Spring Boot会自动处理YAML解析、类型转换、配置验证等工作,无需手动处理
Properties和Jackson转换,完全贴合Spring生态,代码更简洁可维护。
内容的提问来源于stack exchange,提问作者Slevin

