摘要
本文介绍MapStructPlus,也就是MapStruct的加强版,使用注解来简化手写对象转换器。
认识Mapstruct加强版
官网:https://www.mapstruct.plus/
gitee:https://gitee.com/easii/mapstruct-plus
关键注解:
- 会默认生成类和目标类的双向转换接口
@AutoMappers({
@AutoMapper(target = UserDto.class),
@AutoMapper(target = UserVO.class)
})
// 或者
@AutoMapper(target = UserDto.class)
// 使用
User user= Converter.convert(UserDto, User.class);
- 作用在类字段上
@AutoMapping(target = "目标字段")
@AutoMapping(target = "目标日期字段", dateFormat = "yyyy-MM-dd HH:mm:ss")
@AutoMapping(target = "目标数值字段", numberFormat = "$#.00", defaultValue = "100")
@AutoMapping(target = "目标字段", expression = "java(java.lang.String.join(",", source.getEducationList()))")
- 可以自定义类型转换器,同时使用uses绑定
//使用
@AutoMapper(target = User.class, uses = StringToListString.class)
//定义
@Component
public interface StringToListString {
default List<String> stringToListString(String str) {
if (str == null) {
return Collections.emptyList();
}
return Arrays.asList(str.split(","));
}
}
示例代码 [SpringBoot]
1)引入依赖
<!-- 依赖和插件 -->
<dependencies>
<dependency>
<groupId>io.github.linpeilie</groupId>
<artifactId>mapstruct-plus-spring-boot-starter</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.7.18</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<path>
<groupId>io.github.linpeilie</groupId>
<artifactId>mapstruct-plus-processor</artifactId>
<version>1.5.0</version>
</path>
<!-- Lombok处理器 防止lombok和mapstruct冲突 致使lombok注解失效 -->
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</path>
<!-- 最新正式版是 0.2.0(或 0.1.0),而不是跟随 Lombok 主版本 -->
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
2)定义对象A
package org.coffeebeans.entity;
import io.github.linpeilie.annotations.AutoMapper;
import io.github.linpeilie.annotations.AutoMapping;
import lombok.Builder;
import lombok.Data;
import org.coffeebeans.config.StringToListString;
import java.math.BigDecimal;
/**
* <li>ClassName: User </li>
* <li>Author: OakWang </li>
*/
@Data
@Builder
@AutoMapper(target = UserDto.class, uses = StringToListString.class)
public class User {
private Integer id;
@AutoMapping(target = "name")
private String username;
@AutoMapping(target = "age", defaultValue = "100")
private Integer age;
@AutoMapping(target = "familyAddress")
private String address;
@AutoMapping(target = "money", expression = "java(new java.math.BigDecimal("3000"))")
private BigDecimal money;
}
3)定义对象B
package org.coffeebeans.entity;
import io.github.linpeilie.annotations.AutoMapper;
import lombok.Data;
import java.math.BigDecimal;
/**
* <li>ClassName: UserDto </li>
* <li>Author: OakWang </li>
*/
@Data
@AutoMapper(target = User.class)
public class UserDto {
private Integer id;
private String name;
private Integer age;
private String familyAddress;
private BigDecimal money;
}
4)测试对象转换
package org.coffeebeans;
import org.coffeebeans.entity.User;
import org.coffeebeans.entity.UserDto;
import org.junit.jupiter.api.Test;
import io.github.linpeilie.Converter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* <li>ClassName: MapstructTest </li>
* <li>Author: OakWang </li>
*/
@SpringBootTest
public class MapstructPlusTest {
@Autowired
private Converter converter;
@Test
public void test() {
// 创建一个User对象
List<User> userList = new ArrayList<>();
User user = User.builder().id(1).age(null).username("姓名1").address("地址1").money(null).build();
userList.add(user);
// 使用UserTransform将User对象转换为UserDto对象
UserDto userDto = converter.convert(user, UserDto.class);
List<UserDto> userDtos = converter.convert(userList, UserDto.class);
// 验证转换结果
System.out.println("id属性是否相等:" + Objects.equals(user.getId(), userDto.getId()));
System.out.println("name属性是否相等:" + Objects.equals(user.getUsername(), userDto.getName()));
System.out.println("age属性是否相等:" + Objects.equals(user.getAge(), userDto.getAge()));
System.out.println("address属性是否相等:" + Objects.equals(user.getAddress(), userDto.getFamilyAddress()));
System.out.println("money属性是否相等:" + Objects.equals(user.getMoney(), userDto.getMoney()));
System.out.println("User对象:" + user);
System.out.println("UserDto对象:" + userDto);
System.out.println("User集合:" + userList);
System.out.println("UserDto集合:" + userDtos);
/*
输出:
id属性是否相等:true
name属性是否相等:true
age属性是否相等:false
address属性是否相等:true
money属性是否相等:false
User对象:User(id=1, username=姓名1, age=null, address=地址1, money=null)
UserDto对象:UserDto(id=1, name=姓名1, age=100, familyAddress=地址1, money=3000)
User集合:[User(id=1, username=姓名1, age=null, address=地址1, money=null)]
UserDto集合:[UserDto(id=1, name=姓名1, age=100, familyAddress=地址1, money=3000)]
*/
}
}
总结:
以上我们了解了MapStruct的加强版MapStructPlus,通过注解可以更加便捷映射对象,省去了手写转换类的步骤,用起来!
关注公众号:咖啡Beans
在这里,我们专注于软件技术的交流与成长,分享开发心得与笔记,涵盖编程、AI、资讯、面试等多个领域。无论是前沿科技的探索,还是实用技巧的总结,我们都致力于为大家呈现有价值的内容。期待与你共同进步,开启技术之旅。