mapstruct 的 mapstruct-processor 自动生成的 Impl 文件中未设置属性值(时好时坏)

配置依赖和注解处理器

...
<properties>
    <org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
</properties>
...
<dependencies>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>${org.mapstruct.version}</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>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${org.mapstruct.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>
...

检查

  1. source 类型中有私有字段对应的 getXXX()
  2. target 类型中有私有字段对应的 setXXX()

如果使用了 lombok 自动生成 getter/setter,那么一定要注意 annotationProcessorPaths 中的处理顺序,确保 lombok 的注解处理器在 mapstruct 的注解处理器之前。这里还没研究过,但从实验结果来看,maven-compiler-plugin 应该是按顺序来执行 annotationProcessorPaths 下的节点,如果在 mapstruct 处理之前没有 getter/setter,那么得到的 Impl 类里面只会 new TargetClass(),然后就 return 了,不会 mapping properties

<annotationProcessorPaths>
    <path>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${org.projectlombok.lombok.version}</version>
    </path>
    <path>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-processor</artifactId>
        <version>${org.mapstruct.version}</version>
    </path>
</annotationProcessorPaths>
原文地址:https://www.cnblogs.com/myesn/p/mapstruct-working-with-lombok.html