配置依賴和注解處理器
...
<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>
...
檢查
- source 類型中有私有字段對應的 getXXX()
- 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>