一、背景
我們在使用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));
}