.
带你读《2022技术人的百宝黑皮书》——MapStruct,降低无用代码的神器(6)https://developer.aliyun.com/article/1339758?groupCode=taobaotech
子类字段互转
@Mapper public abstract class Converter { public static Converter INSTANT = Mappers.getMapper(Converter.class); @Mapping(target = "config.age", source = "age") @Mapping(target = "config.userNick", source = "userNick") abstract DTO convertToDTO(VO source); @Mapping(target = "age", source = "config.age") @Mapping(target = "userNick", source = "config.userNick") abstract VO convertToVO(DTO dto); }
使用示例
final VO vo = VO.builder() .id(1L) .age(10L) .gmtCreate(new Date()) .userNick("nick") .build(); final DTO dto = Converter.INSTANT.convertToDTO(vo); System.out.println(dto); final VO newVo = Converter.INSTANT.convertToVO(dto); System.out.println(newVo);
输出:
1DTO(id=1, gmtCreate=Fri Sep 16 00:09:05 CST 2022, config=DTO.Config(age=10, userNick=nick)) 2VO(id=1, gmtCreate=Fri Sep 16 00:09:05 CST 2022, age=10, userNick=nick)
利用Spring进行依赖注入
本文以上示例代码中,都是使用Converter.INSTANT来获得Convert实例,这在业务代码中可能显得有些突兀, 而MapStruct提供了依赖注入的机制,让我们能够在Spring的环境下,更优雅的获得Converter,以下是一个例 子:
转换器
该转换器转换字段完全相同的两个类:
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public abstract class Converter { public abstract Target convert(Source source); }
与原有Converter相比,我们删除了丑陋的INSTANT声明:
public static Converter INSTANT = Mappers.getMapper(Converter.class);
并修改了Mapper注解为:
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING)
使用示例
在Spring上下文中,可以直接使用依赖注入注解(Autowired、Resource)获得对应的Converter
@Controller public class MainController { @Resource private Converter convert; @GetMapping("/") @ResponseBody public boolean test() { final Source source = Source.builder() .id(1L) .age(18L) .userNick("nick") .build(); final Target result = convert.convert(source); System.out.println(result); return true; } }
输出:
Target(id=1, age=18, userNick=Nick)
带你读《2022技术人的百宝黑皮书》——MapStruct,降低无用代码的神器(8)https://developer.aliyun.com/article/1339756?groupCode=taobaotech