Using Lombok and MapStruct in a Maven Project

Lombok is a java library providing annotations for boilerplate generation. It will handle getters, setters, toStrings, hashCodes, equals, constructors, builders and even injecting Slf4j loggers into you classes. It’s a very powerful addition to Java. MapStruct is a code generator that greatly simplifies the implementation of mappings between Java bean types based on a convention over configuration approach.

When you add Lombok to the classpath, the annotation processing is picked up automatically with no problem. However, MapStruct does not automatically get picked up and requires an addition to the annotationProcessorPaths configuration of the maven-compiler-plugin. However, when the annotationProcessorPaths is explictly defined by the compiler plugin, then Lombok processor no longer gets automatically invoked.

To fix the issue, you simply need to add both annotation processors into the annotationProcessorPaths configuration. Now you can create MapStruct mappers that use Lombok getters/setters.

<properties>
...
    <lombok.version>1.18.22</lombok.version>
    <mapstruct.version>1.4.2.Final</mapstruct.version>
...
</properties>

<dependencies>
...
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
    </dependency>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>${mapstruct.version}</version>
    </dependency>
...
<dependencies>

<build>
    <plugins>
         ...
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${compiler-plugin.version}</version>
            <configuration>
                <parameters>${maven.compiler.parameters}</parameters>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>${lombok.version}</version>
                    </path>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${mapstruct.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
        ...
    </plugins>
</build>

Leave a Reply

Your email address will not be published. Required fields are marked *