Thursday 14 February 2019

Sling Models vs WCMUSEPOJO

AEM component back-end logic was shifted over years from JSP’s to WCMUse class to WCMUsePOJOs and then to Sling Models.

AEM 6.1 or 6.2 were supporting WCMUsePojo class; AEM 6.2 and 6.3 started to support the Sling Models approach.

Both WCMUsePOJOs and Sling Models are used with HTL using <data-sly-use> block.

Before we jump into the difference , let us understand the concepts.

What is a POJO(Plain Old Java Objects)?

POJO's are simple Java classes which doesnt depend on other libraries, interfaces or annotations. This increases the chance that this can be reused in multiple project types. POJO's provides Getter and Setter methods, which allow you to change the underlying data type without breaking the public interface of your class which makes it more robust and resilient to changes.

What if there are no getters and setters?

Say we havent created setter and getter methods, then any one can directly call the variable and it surely will affect to the code, which may lead to security issues. Here POJO class are forcing other coder to call on the methods rather than directly calling the Instance variables.

What is Sling Models?

Sling Models are annotation driven POJOs. They allows to map resource properties, assign default values, inject OSGI services and much more.

Sling Models are pure POJOs that gives wonderful separation between logic and presentation which also extensible with custom injectors and annotations. Sling Models let you map Java objects to Sling resources. 

Use API Vs Sling Model


HTL(Formerly known as Sightly) uses  two ways of implementing support for business logic objects:
1) Java Use-API, through POJOs,
2) JavaScript Use-API,

Regular POJOs that extend WCMUsePojo implement the Use interface and are initialized with the scripting bindings, providing convenience methods for accessing commonly used objects like request, resource, properties, page etc.

HTL implementation from Sling provides the basic POJO support through the interface and the JavaUseProvider, whereas the use function is implemented by the bundle.

The Sling implementation provides a few extensions to the Use-API.

Sling Model API:

Sling Models are more flexible which can also be used outside HTL, thus makes the business-logic more reusable. They are managed by Sling and can be injected references to other objects using annotations and reflection.

Click on image to see it big

Conversion from WCMUsePojo to SlingModel
Just by adapting the above said methods (Remove 'Extends WCMUse', Add sling model annotation on top of the class, then add inject methods to invoke the references.) a developer can easily convert WCMUsePojo to SlingModel.


For the versions AEM 6.3, AEM 6.4 and AEM Core WCM Components, Adobe recommends using Sling Models as the best practice.
More Details Here


Video of the comparison 

Read More:

Sling Model Vs Sling Model Exporter

No comments:

Post a Comment