MapStruct与lombok加载顺序问题与annotationProcessorPaths的关系?


MapStruct是什么?

MapStruct is a code generator that greatly simplifies the implementation of mappings between Java bean types based on a convention over configuration approach.——https://mapstruct.org/
从官方定义来看,MapStruct类似于我们熟悉的BeanUtils, 是一个Bean的转换框架。
In contrast to other mapping frameworks MapStruct generates bean mappings at compile-time which ensures a high performance, allows for fast developer feedback and thorough error checking.——https://mapstruct.org/
他与BeanUtils最大的不同之处在于,其并不是在程序运行过程中通过反射进行字段复制的,而是在编译期生成用于字段复制的代码(类似于Lombok生成get()和set()方法),这种特性使得该框架在运行时相比于BeanUtils有很大的性能提升。

lombok

这个大家都很熟悉,生成getset方法,那么mapstuct要依赖这种方法。

MapStuct与lombok的引入的正确关系

由于MapStruct和Lombok都会在编译期生成代码,如果配置不当,则会产生冲突,因此在工程中同时使用这两个包时,应该按照以下方案导入:

当POM中不包含Lombok时


    org.mapstruct
    mapstruct
    1.5.2.Final


    org.mapstruct
    mapstruct-processor
    1.5.2.Final

当POM中包含Lombok且不包含https://mapstruct.org/documentation/installation/

...

1.5.2.Final

...


org.mapstruct
https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#annotationProcessorPaths

https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#annotationProcessorPaths

我们接下来以下命令来获取当前Maven项目中的classpath:

mvn dependency:build-classpath -Dmdep.outputFile=classPath.txt
从导出内容可以看出,classPath中的Jar包顺序就是与dependencies中导入的顺序是相同的。

自此,关于MapStruct导入顺序的所有问题均已经被解决,总结如下:

在POM中没有annotationProcessorPaths时,Maven使用的classPath作为注解处理器执行的顺序,而classPath的顺序正是dependencies中导入的顺序。
当MapStruct依赖在Lombok依赖前面时,在执行注解处理器期间, 由于Lombok还未生成get、set代码,因此在MapStruct看来,这些类并没有公开的成员变量,也就无从生成用于转换的方法。
在使用annotationProcessorPaths后,其强制规定了注解处理器的顺序,dependencies中的顺序就被忽略了,Maven一定会先运行Lombok再运行MapStruct,代码即可正常运行。