一、背景
我们在使用JAVA开发项目的过程中经常遇到很多对象转换的场景,例如 DO、DTO、BO、AO、VO等对象间的转换,之前自己都是手写,最近发现了一个好用的工具—MapStruct,下面推荐给大家。
二、MapStruct
1. git地址:
https://github.com/mapstruct/mapstruct?spm=ata.13261165.0.0.49823fc0pcr5Q9
2.示例:
下面有两个类,需要进行转换:
public class Car {
private String make;
private int numberOfSeats;
private CarType type;
//constructor, getters, setters etc.
}
public class CarDto {
private String make;
private int seatCount;
private String type;
//constructor, getters, setters etc.
}
(1)手写实现
public class CarConvertor {
public static Car CarDtoToCar(CarDto carDto) {
if (carDto == null){
return null;
}
Car car = new Car();
car.setMake(carDto.getMake());
car.setNumberOfSeats(carDto.getSeatCount());
car.setType(carDto.getType());
return car;
}
(2)MapStruct 实现
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@Mapping(source = "seatCount", target = "numberOfSeats")
Car carDtoToCar(CarDto carDto);
}
public static void main(String[] args) {
CarDto carDto = new CarDto( "Morris", 5, CarType.SEDAN );
Car car = CarMapper.INSTANCE.carDtoToCar(carDto);
System.out.println(Json.toString(car));
}