October 13, 2020
Estimated Post Reading Time ~

Using Project Lombok in AEM Sling Models - AEM 6.5

Most of the time in our projects we end up creating plain Sling models for dialogs value or for some performing some operations.

In some cases we just need a plain Sling Model where we just want to Inject some variables or create some variable and generate getters and setters for the same , also if you have around more than 20+ variables then you have to first declare those variables and then generate corresponding Getters and Setters which increases the size of your Java class by adding around 60+ extra line of code (if 20 variables).

In such scenarios we can make use of Project Lambok Library to get the Getters and Setters generated at runtime.

Add following maven dependency:
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
    
<scope>provided</scope>
</dependency>


After adding this dependency you can start using this library in your Java classes, Below is the example that I tested out in my AEM Sling Model:

Code Snippet
Once you add the @Getter annotation it automatically declares the getter method to the variable, you can verify in the outline in Eclipse.

Getter corresponding to the variable
Same way we can use @Setter annotation as well to declare the setters at runtime. If you looking for using both, you can use @Data annotation at the class level and it automatically imports all the Getter and Setters at runtime. 

Using @Data annotation


Getter and Setter corresponding to variable
NOTE: 
Sometimes after adding the dependency you won't see the reference of Getters or Setters in Outline then in that case your methods won't be generated at runtime. So please make sure it's the part of the Outline.

If it's not showing up the go-to 
..m2\repository\org\projectlombok\lombok\1.18.4repository in you local and run the java -jar lombok-1.18.4.jar to run the Jar and you will see the following window opens up, Just provide the path of the IDE that you are using and click on Install/Update. And restart the IDE to see the effect.



Project Lombok Library comes with more features that can help you to spice up your Java code and reduces most of the manual effort.

Came to know from one of a friend regarding as he was implementing the same in the Spring application. So I thought why not it a try to use it as part current AEM Archetype project.
This is tested on AEMaaCs and AEM 6.5.5.

If you need more inputs or any update on the above article, please DM me on LinkedIn or email.

Reference: 


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.