原创

MapStruct使用和原理

MapStruct用于对象之间的转换,例如DTO转PO

使用:

1.加入引用

        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>1.4.2.Final</version>
        </dependency>

2.配置注解处理器

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source> <!-- depending on your project -->
                    <target>1.8</target> <!-- depending on your project -->
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>1.18.20</version>
                        </path>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>1.4.2.Final</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>

3.代码演示

public class MapStructDemo {
    public static void main(String[] args) {
        AppleDO appleDO = new AppleDO();
        appleDO.setName("aaa");
        AppleDTO appleDTO = MapStructMapper.INSTANCE.appleDO2DTO(appleDO);
        System.out.println(appleDTO.getName());
    }
    @Mapper
    interface MapStructMapper {
        MapStructMapper INSTANCE = Mappers.getMapper(MapStructMapper.class);
        AppleDTO appleDO2DTO(AppleDO appleDO);
    }
}
@Data
class AppleDTO {
    private String name;
}
@Data
class AppleDO {
    private String name;
}

4.需要先maven编译成功,会在目录target\generated-sources\annotations生成实现类,然后就可以调用测试了

正文到此结束