Sling Models is framework that will let us map Sling objects to POJOs. The idea is to create model objects to represent resources.
This approach uses entirely annotations to build its structure, and has support to work with both classes and interfaces.
On this post I will explain how to incorporate sling models into your project to map resources into POJOs.
SLING MODEL Bundles
AEM 6 has Sling Models support OOTB, to make it work with CQ5.6 some extra steps will have to be followed. In my case, I am using AEM 6 SP2.
To find out if your AEM/CQ installation is Sling Model ready you can visit the web console and check if the OSGI bundle for Sling Model exists and verify that it is active.
To do that you can visit the /system/console/bundles URL in your local instance and look for the Sling Model bundles.
Note: Take a close look at the bundles version.
Project Setup
Once your AEM instance is ready you can begin the project setup:
First you will have to create a Java project that later will be deployed into OSGI as a bundle. This bundle will have the Sling Model packages.
The POM of this project needs to have the maven-bundle-plugin declaration like in the following screenshot.
The <Sling-Model-Packages>section is very important. This will let OSGI know that the package path described there contains Sling Models classes/interfaces, and it will scan through it looking for the annotations. PLEASE don’t skip these plugin lines otherwise your models might not be mapped correctly.
SLING Model Interface or Class
Now you are ready to create models either using classes or interfaces. There are several annotations that will help you on this setup. The most common annotations are:
@Model Used to specify that the class represents a Sling Model.
@Inject Used to specify that a property represents a resource property.
Note: There are several others annotations and variations for Sling Models that might suite for different needs.
On my test case I've declared a UserInfo interface with two properties. The properties will be injected using the getter declarations.
Now that we have our Sling Model ready, we just need to test it, for this I've created a simple servlet that pulls the resource and adapts it to our Sling Model.
The test Servlet will pull the resource by using the resource resolver:
Then you can just print the different properties using the userInfo object.
Same thing you can do in an AEM component JSP, you just need to adapt the resource to the Sling Model.
As I said earlier, using Sling Models is a great approach to handle different scenarios, including coding unit tests. Also this is just a simple test case, there is a bunch of different scenarios where extended approaches can be implemented.