Project Lombok in AEM Projects

Published
In AEM backend Java development, Sling Models are utilized to retrieve dialog values using annotations. However, writing boilerplate code such as getter methods for passing these values to HTL can be tedious. To simplify this process, Project Lombok can be integrated, automatically generating the necessary boilerplate code with annotations like @Getter. This streamlines development tasks by eliminating the need for manual getter method creation.
Lombok is a Java library designed to minimize boilerplate code by providing annotations to generate getters, setters, constructors, and other repetitive code structures. By leveraging Lombok, developers can produce cleaner and more concise code without sacrificing functionality. To incorporate Lombok into the AEM project, you'll need to include the Maven dependency in both the root and core pom.xml files.
pom.xml
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency>
core / pom.xml
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
For the demonstration purpose, let's consider a component with a dialog comprising a textfield (title), tagfield (tags), datepicker (publishDate), and select (category) field. In a Sling Model, the typical approach involves creating getter methods for each variable needed for access from HTL
Article.java
public class Article { @ValueMapValue String title; @ValueMapValue String[] tags; @ValueMapValue Date publishDate; @ValueMapValue String category; public String getTitle() { return title; } public String[] getTags() { return tags; } public Date getPublishDate() { return publishDate; } public String getCategory() { return category; } }
By leveraging Lombok, we can enhance the Article Sling Model as follows. @Getter annotation instructs Lombok to automatically generate getter methods for the fields within the class.
Article.java
import lombok.Getter; public class Article { @Getter @ValueMapValue String title; @Getter @ValueMapValue String[] tags; @Getter @ValueMapValue Date publishDate; @Getter @ValueMapValue String category; }