What is the Sling Models?
While working with Sling in Adobe Experience Manager[AEM]; we need to map our objects (Java backend object) with Apache Sling resource. Many Sling projects want to be able to create model objects - POJOs which are automatically mapped from Sling objects, typically resources, but also request objects. With the help of sling models, we can define a model object "a Java class or interface" and map that object with sling resources. Before sling models, we are achieving these all using WCMUse and WCMUsePojo which are quite similar to sling models.
To use the Sling Models in your project first you need to add the following dependency in your pom.xml file.
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.model.api</artifactId>
<version>1.3.0</version>
<scope>provided</scope>
<dependency>
@Model annotation
To map a java class or interface with sling resource we use @Model annotation and could pass an adaptables parameter into it to make a class adaptable by sling model.
@Model(adaptables = Resource.class)
public class RashidJorvee {
//Write your code here
}
or
@Model(adaptables = SlingHttpServletRequest.class)
public class RashidJorvee {
//Write your code here
}
@Inject annotation
Using @Inject we can make a filed and method injectable. We can also inject a constructor using @Inject annotation. We also use @Inject with @Filter option to pass the reference to an available OSGi service, which works similarly as @Refernce.
@Inject
private String firstName;
@Inject
String getName();
There are many other options we have which makes injection make accurate and exact. like following
@Named
To match the name of the property with the field name
@Via
Change the adaptable object instead of using the original adaptable object
@Default
To assign a default value to any field or property.
@Filter
Filter an OSGi service
@Optional
Mark filed and method injection optional.
@Source
To manage the ambiguity between injectors, it helps us to tie the injected field or method to a particular injector.
@PostConstruct annotation
Using PostConstruct annotation we can invoke any method which we want to execute when all injection has been completed for that class. This is act as similar to the activate() method which we use for WCMUsePojo or WCMUse.
@PostConstruct
public void letMeExecuteFirst() {
//Write your code here;
}
No comments:
Post a Comment
If you have any doubts or questions, please let us know.