MapStruct 代替BeanUtil

冷暖自知 提交于 2020-05-08 15:23:56

这篇博文不错:https://www.cnblogs.com/tanoak/articles/10302299.html

 

1.pom.xml配置

<dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>1.2.0.Final</version>
        </dependency>  

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>1.2.0.Final</version>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>1.18.10</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>

 

2.java实体代码

 1 @Data
 2 public class CarDto {
 3 
 4     private String make;
 5     private int seatCount;
 6     private String type;
 7 }
 8 
 9 
10 @Data
11 @AllArgsConstructor
12 public class Car {
13     private String make;
14     private int numberOfSeats;
15 }

 

3.定义一个mapper接口,里面做实体装换

1 @Mapper
2 public interface CarMapper {
3 
4     CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
5 
6     @Mapping(source = "numberOfSeats", target = "seatCount")
7     CarDto carToCarDto(Car car);
8 
9 }

 

4.最后测试代码

 1 public class Test {
 2 
 3     public static void main(String[] args) {
 4         Car car = new Car( "Morris", 120 );
 5         //转换对象
 6         CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
 7 
 8         //测试
 9         System.out.println( carDto );
10         System.out.println( carDto.getMake() );
11         System.out.println( carDto.getSeatCount() );
12         System.out.println(carDto.getType());
13     }
14 }

 

 

还有其他高级用法....

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!