问题描述
在工作中,我们在许多带有 Java 8 REST Full 应用程序的 SpringBoot 项目中使用 MapStruct,当我们需要将实体映射到 DTO 或 DTO 到响应或类似情况时。但是今天我的朋友向我展示了使用简单的转换器代替 MapStruct 的巨大优势。
这是一个使用 MapStrurct 的简单示例:
@Mapper(componentModel="spring",unmappedTargetPolicy = ReportingPolicy.IGnorE)
public interface AccountMapper {
@Mapping(source = "customerBank.customerId",target = "customerId")
AccountResponse toResponse(AccountBank accountBank);
}
它运行良好,但实际上如果有人将 customerId 属性更改为另一个名称而忘记更改此映射器,我们将遇到运行时错误。
Converter 的优点是我们会出现编译时错误并避免运行时错误。
请让我知道是否有人设法分享如何避免运行时错误,就像我提出的场景一样,使用 MapStruct,因为 Converter 没有带来同样的优势。
我的问题是:是否可以高效地使用 MapStruct,我的意思是没有容易出错的运行时错误?
解决方法
如果我理解得很好,您会希望在使用 MapStruct 自定义映射的属性命名错误时出现编译时错误。 如果是这样,您应该在 pom.xml 中添加一个必要的构建插件(如果您使用 maven)。
<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>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
当然还要为 MapStruct 版本声明一个属性:
<properties>
<mapstruct.version>1.4.1.Final</mapstruct.version>
</properties>
项目编译完成后,加上插件,注解处理器会生成完整的实现:
public class AccountMapperImpl implements AccountMapper
在 target\generated-sources\annotations 文件夹中。
您可以检查实现类的生成源,所有设置和仔细检查。
如果 @Mapping
注释中的属性名称不存在,编译器将抛出错误。