程序人生javamapstruct
逐暗者什么是mapstruct?
一种属性复制、对象转换的工具。在java项目中,无论是MVC还是DDD模型,都少不了各种对象,例如DO、BO、DTO、VO 等等,那么对象转换就成了比较头疼的一个事情了。
如何解决对象转换?
对象互相转换有以下几种方法
- BeanUtils.copy为代表的自动复制属性工具,优点是较少了大量赋值语句,使代码可读性大大提高。缺点也很明显,基于运行时反射等的手段去获取对象结构并赋值,性能显然会有所下降。
- 以generateO2O为代表的idea插件,通过代码生成的方式将对象转换语句写入源码。性能自然没有什么可挑剔的,但可读性非常的差。有些对象有20~30个属性时,对象转换方法内语句非常多,可维护性也不好,后期增加修改属性,很难修改到所有地方。
- 以mapstruct为代表的,在编译时期自动生成class,既避免了运行时性能的下降,又使得源码比较简单,提升了可读性。
如何使用mapstruct?
引入mapstruct
1 2 3 4 5 6 7 8 9 10 11
| <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> <version>1.2.0.CR1</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.2.0.CR1</version> <scope>provided</scope> </dependency>
|
静态对象方式使用
1 2 3 4 5 6 7 8 9
| @Mapper public interface StructMapper {
public static StructMapper INSTANCE = Mappers.getMapper(StructMapper.class);
@Mapping(source = "desc", target = "display") TestVO do2Vo(TestDO TestDO);
}
|
1 2 3 4 5
| public static void main(String[] args) { TestDO testDO = new TestDO().setName("name").setDesc("说明"); TestVO testVO = StructMapper.INSTANCE.do2Vo(testDO); System.out.println(JSON.toJSONString(testVO)); }
|
- 属性名称时,会自动转换(赋值),名称不一样时可以使用注解@Mapping(source = “源名称”, target = “目标名称”)来进行申明抓换。
spring管理方式
1
| @Mapper(componentModel = "spring")
|
使用 componentModel = ”spring“ 就可以将接口的实例交由spring管理,我们只用注入接口即可。(实现类是在编译期间生成的)
其他
注解上有一些格式化方式、null值处理、默认值、自定义转换等属性可以进行配置,用来达到不同的转换效果。
多个入参转换
1 2 3
| @Mapping(source = "student.id", target = "studentId") @Mapping(source = "teacher.id", target = "teacherId") StudentTeacherDto toUserRoleDto(Student student, Teacher teacher);
|
更新值
1 2
| @Mapping(source = "id", target = "studentId") void update(Student student, @MappingTarget StudentTeacherDto studentTeacherDto);
|