- What are Sling Models?
- Why Sling Models?
- WCMPojo VS Sling Models?
- Getting started with Sling Models
- Basic Sling Model Annotations
- Available Injectors
- Sling Models Exporter
Basic AEM Terminologies
- OSGi - Open System Gateway Initiative
- JCR - Java Content Repository
- Apache Sling
What are Sling Models?
Before jumping on to Sling Models directly, let's see what are models?
Models are :
- classes which encapsulate closely related items for eg: ProductDataModel
- classes which usually are used to define the domain objects
- classes which lets us implement MVC design patterns
Sling Models are :
- pure POJO classes, driven by annotations
- classes which OOTB, support resource properties (via ValueMap), SlingBindings, OSGi services, request attributes
- classes which lets us adapt multiple objects - minimal required Resource and SlingHttpServletRequest
- Adapter Pattern: The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.
Sling models are POJO classes in which properties of the adaptable interfaces/classes can be injects and hence reducing the boilerplate code
Taglibs/Java Models-> WCMUsePojo -> Sling Models
- Before sling Models, we used have problems like boiler plate code & reusing code was difficult
- while sling Models were initially introduced to make Adapter pattern easier to implement with custom code
- Around the same time as Sling models a new templating framework called “Sightly” was introduced
Quick Demo of code Before Sling Models
Why Sling models?
- Reduces code Redundancy
- Makes code more maintainable
- Reduced coding efforts
Getting started with Sling Models
- Add the sling model dependency
- Create a package under which all the Sling Models will reside
- Add package path as “Sling-Model-Packages” property of “maven-bundle-plugin”
- Next create a Class or Interface in the newly created package & add the “@Model” annotation on Class
- Use @Inject annotation to inject a field from adaptable class defined in @Model annotation
WCMPojo v/s Sling Models
- WCMPojo is an abstract class which implements Use interface
- Class extending WCMPojo abstract class is initialised with the scripting bindings, providing convenience methods for accessing commonly used objects
- Sling Models helps you reduce the code even futher using @Inject, hence making your code even more maintainable
- Sling Models can be even used outside of HTL/Sightly, which makes Sling Models even more reusable
Basic Sling Annotations
For details of each annoation please refer the documentation
Quick Intro to Sling Model Exporter Framework
Along with Sling Models 1.3.0 there was a new framework introduced known as Sling Model Exporter Framework. Sling Model Exporter framework comes with Jackson Exporter that automatically serializes an “Ordinary” sling model object into JSON