SlideShare a Scribd company logo
1 of 38
Download to read offline
Sling Models in AEM
(by Ankur Chauhan)
Agenda
Agenda
1. What are Sling Models?
Agenda
1. What are Sling Models?
2. Why Sling Models?
Agenda
1. What are Sling Models?
2. Why Sling Models?
3. How to use Sling Models in AEM?
Agenda
1. What are Sling Models?
2. Why Sling Models?
3. How to use Sling Models in AEM?
4. Sling Model Annotations with Demo.
Agenda
1. What are Sling Models?
2. Why Sling Models?
3. How to use Sling Models in AEM?
4. Sling Model Annotations with Demo.
“Sling models are pure Plain Old Java Objects (POJO), which
are automatically mapped from Sling objects, typically
resource and request objects. We can also inject OSGi
Services in these models as well.”
➢
These are "Pure" POJOs.
➢
Use standard annotations where possible.
➢
OOTB, support resource properties (via ValueMap), SlingBindings, OSGi services,
request attributes
➢
Adapt multiple objects - minimal required Resource and SlingHttpServletRequest
➢
Client doesn't know/care that these objects are different than any other adapter
factory
➢
Support both classes and interfaces.
➢
Work with existing Sling infrastructure (i.e. not require changes to other bundles).
Design Goals
Agenda
1. What are Sling Models?
2. Why Sling Models?
3. How to use Sling Models in AEM?
4. Sling Model annotations with Demo.
➢
Using Sling Models you can do more with less code
➢
You can reduce your coding efforts.
➢
Your code is more maintable using Sling Modes.
➢
You don't have to write redundent code.
It is more understandable using a live scenario. (Native Ecommerce API in AEM)
Agenda
1. What are Sling Models?
2. Why Sling Models?
3. How to use Sling Models in AEM?
4. Sling Model annotations with Demo
Dependency Required
➢
If you are working with AEM6 then you have org.apache.sling.models.api package
already present in your AEM instance.
Dependency Required
➢
If you are working with AEM6 then you have org.apache.sling.models.api package
already present in your AEM instance.
➢
If you are using earlier version of AEM then you have to download this package from
Sling website and then install it at your AEM instance.
Dependency Required
➢
If you are working with AEM6 then you have org.apache.sling.models.api package
already present in your AEM instance.
➢
If you are using earlier version of AEM then you have to download this package from
Sling website and then install it at your AEM instance.
➢
You can find all the Sling Models Injectors at
http://localhost:4502/system/console/status-slingmodels
Dependency Required
➢
If you are working with AEM6 then you have org.apache.sling.models.api package
already present in your AEM instance.
➢
If you are using earlier version of AEM then you have to download this package from
Sling website and then install it at your AEM instance.
➢
You can find all the Sling Models Injectors at
http://localhost:4502/system/console/status-slingmodels
➢
Maven dependecy for your project can be found at-
Dependency Required
➢
It depends on your AEM version so best way is to find this dependency at your on AEM instance
for that you can search for – org.apache.sling.models
in felix console bundles tab. Or
➢
Go to Felix Console packages tab And search for org.apache.sling.models.annotations.Model
it you will get the Maven dependency for your project.
Dependency Required
➢
It depends on your AEM version so best way is to find this dependency at your on AEM instance
for that you can search for – org.apache.sling.models
in felix console bundles tab. Or
➢
Go to Felix Console packages tab And search for org.apache.sling.models.annotations.Model
it you will get the Maven dependency for your project.
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.models.api</artifactId>
<version>1.0.0</version>
<scope>provided</scope>
</dependency>
➢
Now add this dependency to your project.
➢
Search for maven-scr-plugin in your parent pom.xml file.
➢
Update it with
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Sling-Model-Packages> sling.models </Sling-Model-Packages>
<Bundle-Category>sling-model-demo</Bundle-Category>
</instructions>
</configuration>
</plugin>
➢
This plugin modification is mandatory so that this header must be added to the
bundle's manifest file.
Agenda
1. What are Sling Models?
2. Why Sling Models?
3. How to use Sling Models in AEM?
4. Sling Model annotations with Demo
Annotations
➢
@Model
➢
@Inject
➢
@Optional
➢
@Default
➢
@Named
➢
@PostConstruct
➢
@Via
➢
@Source
➢
@Required
➢
List<Resource> list.
Before starting with these annotations, Let's have a look on this line of code.
resource.adaptTo(ValueMap.class);
In this code snippet -
➢
resource will behaves as an adaptable
➢
ValueMap behaves as an adapter
Code Snippet Part - I
@Model(adaptables = Resource.class )
public class ResourceValues {
...
}
Code Snippet Part - I
@Model(adaptables = Resource.class )
public class ResourceValues {
@Inject // If defined then Resource must have this property else it will return null.
private String firstName;
}
Code Snippet Part - I
@Model(adaptables = Resource.class )
public class ResourceValues {
@Inject // If defined then Resource must have this property else it will return null.
private String firstName;
/* To provide default value to this string for Strings & primitives, Default only works with
@Inject annotation not with @Optional annotation. */
@Inject @Default(values="defaultValue")
private String lastName;
}
Code Snippet Part - I
@Model(adaptables = Resource.class )
public class ResourceValues {
@Inject // If defined then Resource must have this property else it will return null.
private String firstName;
/* To provide default value to this string for Strings & primitives, Default only works with
@Inject annotation not with @Optional annotation. */
@Inject @Default(values="defaultValue")
private String lastName;
/* If the field or method name doesn't exactly match the property name */
@Inject @Named("secondPropertyName")
private String otherName;
}
Code Snippet Part - I
@Model(adaptables = Resource.class )
public class ResourceValues {
@Inject // If defined then Resource must have this property else it will return null.
private String firstName;
/* To provide default value to this string for Strings & primitives, Default only works with
@Inject annotation not with @Optional annotation. */
@Inject @Default(values="defaultValue")
private String lastName;
/* If the field or method name doesn't exactly match the property name */
@Inject @Named("secondPropertyName")
private String otherName;
@Optional // If defined then Resource may or may not have property.
private String fullName;
}
Question?
Is it required to add this @optional annotation at every field, if want to make is optional?
Answer ?
Yes, if you are using Sling API version before 1.0.2 and after this version you get another property
in @Model annotation named as defaultInjectionStrategy. After adding this property all the fields
are by default @optional.
But if you wnat some field as required then you have to add @required annotation on that field.
This property is defined in @Model annotation and it's syntex is-
@Model(adaptables=Resource.class,defaultInjectionStrategy=DefaultInjectionStrategy.OPTIONAL)
Code Snippet Part - II
How to use Sling Models in AEM?
ResourceValues resourceValues = resource.adaptTo(ResourceValues.class)
Code Snippet Part - II
How to use Sling Models in AEM?
ResourceValues resourceValues = resource.adaptTo(ResourceValues.class)
How to use in JSP?
<sling:adaptTo adaptable="${resource}" adaptTo="org.apache.sling.models.it.models.MyModel"
var="model"/>
Code Snippet Part - II
How to use Sling Models in AEM?
ResourceValues resourceValues = resource.adaptTo(ResourceValues.class)
How to use in JSP?
<sling:adaptTo adaptable="${resource}" adaptTo="org.apache.sling.models.it.models.MyModel"
var="model"/>
How to use in Sightly?
${sling:adaptTo(resource, 'org.apache.sling.models.it.models.MyModel')}
Code Snippet Part - III
@Model(adaptables = Resource.class)
public class ResourceValues {
/* Child List injection works after Sling version 1.0.6.
This List injection will hold list of all the child nodes present under childs node under
current resource.
*/
@Inject
private List<Resource> childs;
}
Code Snippet Part - III
@Model(adaptables = Resource.class)
public class ResourceValues {
/* Child List injection works after Sling version 1.0.6.
This List injection will hold list of all the child nodes present under childs node under
current resource.
*/
@Inject
private List<Resource> childs;
/*
The @PostConstruct annotation can be used to add methods which
are invoked upon completion of all injections
*/
@PostConstruct
protected void sayHello() {
System.out.println("post construct is working");
}
}
Code Snippet Part - IV
@Model(adaptables=SlingHttpServletRequest.class)
public interface RequestValues {
/* will return
request.getResource().adaptTo(ValueMap.class).get("propertyName", String.class)
*/
@Inject @Via("resource")
String getPropertyName();
}
Means:-
“If the injection should be based on a JavaBean property of the adaptable, you can indicate this
using the @Via annotation”
Code Snippet Part - V
@Model(adaptables=SlingHttpServletRequest.class)
public interface RequestValues {
/* Ensure that "resource" is retrived from the bindings, not a request attribute */
@Inject @Source("script-bindings")
Resource getResource();
}
Questions??
References:
Sling Model Documentation

More Related Content

What's hot

Aem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAshokkumar T A
 
JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?connectwebex
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep DiveGabriel Walt
 
Experience and Content Fragment
Experience and Content FragmentExperience and Content Fragment
Experience and Content FragmentHeena Madan
 
Adobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsAdobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsGabriel Walt
 
SPA Editor - Adobe Experience Manager Sites
SPA Editor - Adobe Experience Manager SitesSPA Editor - Adobe Experience Manager Sites
SPA Editor - Adobe Experience Manager SitesGabriel Walt
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6Yuval Ararat
 
Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6DEEPAK KHETAWAT
 
Adobe AEM core components
Adobe AEM core componentsAdobe AEM core components
Adobe AEM core componentsLokesh BS
 
AEM Best Practices for Component Development
AEM Best Practices for Component DevelopmentAEM Best Practices for Component Development
AEM Best Practices for Component DevelopmentGabriel Walt
 
Adobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job ProcessingAdobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job ProcessingCarsten Ziegeler
 
Rest and Sling Resolution
Rest and Sling ResolutionRest and Sling Resolution
Rest and Sling ResolutionDEEPAK KHETAWAT
 
Architecting an Highly Available and Scalable WordPress Site in AWS
Architecting an Highly Available and Scalable WordPress Site in AWS Architecting an Highly Available and Scalable WordPress Site in AWS
Architecting an Highly Available and Scalable WordPress Site in AWS Harish Ganesan
 
Introduction to Amazon Elasticsearch Service
Introduction to  Amazon Elasticsearch ServiceIntroduction to  Amazon Elasticsearch Service
Introduction to Amazon Elasticsearch ServiceAmazon Web Services
 
An introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel AvivAn introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel AvivAmazon Web Services
 
Introduction to Sightly
Introduction to SightlyIntroduction to Sightly
Introduction to SightlyAnkit Gubrani
 
Sling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak KhetawatSling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak KhetawatAEM HUB
 
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016Amazon Web Services Korea
 

What's hot (20)

Aem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAem dispatcher – tips & tricks
Aem dispatcher – tips & tricks
 
JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?
 
Osgi
OsgiOsgi
Osgi
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
 
Experience and Content Fragment
Experience and Content FragmentExperience and Content Fragment
Experience and Content Fragment
 
Adobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsAdobe Experience Manager Core Components
Adobe Experience Manager Core Components
 
SPA Editor - Adobe Experience Manager Sites
SPA Editor - Adobe Experience Manager SitesSPA Editor - Adobe Experience Manager Sites
SPA Editor - Adobe Experience Manager Sites
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6
 
Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6
 
Adobe AEM core components
Adobe AEM core componentsAdobe AEM core components
Adobe AEM core components
 
AEM Best Practices for Component Development
AEM Best Practices for Component DevelopmentAEM Best Practices for Component Development
AEM Best Practices for Component Development
 
Adobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job ProcessingAdobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job Processing
 
Rest and Sling Resolution
Rest and Sling ResolutionRest and Sling Resolution
Rest and Sling Resolution
 
Architecting an Highly Available and Scalable WordPress Site in AWS
Architecting an Highly Available and Scalable WordPress Site in AWS Architecting an Highly Available and Scalable WordPress Site in AWS
Architecting an Highly Available and Scalable WordPress Site in AWS
 
Introduction to Amazon Elasticsearch Service
Introduction to  Amazon Elasticsearch ServiceIntroduction to  Amazon Elasticsearch Service
Introduction to Amazon Elasticsearch Service
 
An introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel AvivAn introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
 
Introduction to Sightly
Introduction to SightlyIntroduction to Sightly
Introduction to Sightly
 
AWS Fargate on EKS 실전 사용하기
AWS Fargate on EKS 실전 사용하기AWS Fargate on EKS 실전 사용하기
AWS Fargate on EKS 실전 사용하기
 
Sling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak KhetawatSling Models Using Sightly and JSP by Deepak Khetawat
Sling Models Using Sightly and JSP by Deepak Khetawat
 
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
 

Similar to Understanding Sling Models in AEM

Deepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDeepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDEEPAK KHETAWAT
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular IntermediateLinkMe Srl
 
Apikit from command line
Apikit from command lineApikit from command line
Apikit from command linefedefortin
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developerSalvatore Fazio
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
Dependency Injection for PHP
Dependency Injection for PHPDependency Injection for PHP
Dependency Injection for PHPmtoppa
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application FrameworkJady Yang
 
Declaring Server App Components in Pure Java
Declaring Server App Components in Pure JavaDeclaring Server App Components in Pure Java
Declaring Server App Components in Pure JavaAtlassian
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - TryoutMatthias Noback
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumMatthias Noback
 
Painless Javascript Unit Testing
Painless Javascript Unit TestingPainless Javascript Unit Testing
Painless Javascript Unit TestingBenjamin Wilson
 
AEM and Sling
AEM and SlingAEM and Sling
AEM and SlingLokesh BS
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet CampPuppet
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...WordCamp Sydney
 

Similar to Understanding Sling Models in AEM (20)

Deepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDeepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jsp
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
 
Beyond AEM Curl Commands
Beyond AEM Curl CommandsBeyond AEM Curl Commands
Beyond AEM Curl Commands
 
Apikit from command line
Apikit from command lineApikit from command line
Apikit from command line
 
Evolve18 | Abhishek Dwevidi & Varun Mitra | Intro to Backend Development in AEM
Evolve18 | Abhishek Dwevidi & Varun Mitra | Intro to Backend Development in AEMEvolve18 | Abhishek Dwevidi & Varun Mitra | Intro to Backend Development in AEM
Evolve18 | Abhishek Dwevidi & Varun Mitra | Intro to Backend Development in AEM
 
Javascript for the c# developer
Javascript for the c# developerJavascript for the c# developer
Javascript for the c# developer
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
Dependency Injection for PHP
Dependency Injection for PHPDependency Injection for PHP
Dependency Injection for PHP
 
Xopus Application Framework
Xopus Application FrameworkXopus Application Framework
Xopus Application Framework
 
Declaring Server App Components in Pure Java
Declaring Server App Components in Pure JavaDeclaring Server App Components in Pure Java
Declaring Server App Components in Pure Java
 
13 java beans
13 java beans13 java beans
13 java beans
 
Cucumber with appium
Cucumber with appiumCucumber with appium
Cucumber with appium
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - Tryout
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
 
Painless Javascript Unit Testing
Painless Javascript Unit TestingPainless Javascript Unit Testing
Painless Javascript Unit Testing
 
AEM and Sling
AEM and SlingAEM and Sling
AEM and Sling
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 

Understanding Sling Models in AEM

  • 1. Sling Models in AEM (by Ankur Chauhan)
  • 3. Agenda 1. What are Sling Models?
  • 4. Agenda 1. What are Sling Models? 2. Why Sling Models?
  • 5. Agenda 1. What are Sling Models? 2. Why Sling Models? 3. How to use Sling Models in AEM?
  • 6. Agenda 1. What are Sling Models? 2. Why Sling Models? 3. How to use Sling Models in AEM? 4. Sling Model Annotations with Demo.
  • 7. Agenda 1. What are Sling Models? 2. Why Sling Models? 3. How to use Sling Models in AEM? 4. Sling Model Annotations with Demo.
  • 8. “Sling models are pure Plain Old Java Objects (POJO), which are automatically mapped from Sling objects, typically resource and request objects. We can also inject OSGi Services in these models as well.”
  • 9. ➢ These are "Pure" POJOs. ➢ Use standard annotations where possible. ➢ OOTB, support resource properties (via ValueMap), SlingBindings, OSGi services, request attributes ➢ Adapt multiple objects - minimal required Resource and SlingHttpServletRequest ➢ Client doesn't know/care that these objects are different than any other adapter factory ➢ Support both classes and interfaces. ➢ Work with existing Sling infrastructure (i.e. not require changes to other bundles). Design Goals
  • 10. Agenda 1. What are Sling Models? 2. Why Sling Models? 3. How to use Sling Models in AEM? 4. Sling Model annotations with Demo.
  • 11. ➢ Using Sling Models you can do more with less code ➢ You can reduce your coding efforts. ➢ Your code is more maintable using Sling Modes. ➢ You don't have to write redundent code. It is more understandable using a live scenario. (Native Ecommerce API in AEM)
  • 12. Agenda 1. What are Sling Models? 2. Why Sling Models? 3. How to use Sling Models in AEM? 4. Sling Model annotations with Demo
  • 13. Dependency Required ➢ If you are working with AEM6 then you have org.apache.sling.models.api package already present in your AEM instance.
  • 14. Dependency Required ➢ If you are working with AEM6 then you have org.apache.sling.models.api package already present in your AEM instance. ➢ If you are using earlier version of AEM then you have to download this package from Sling website and then install it at your AEM instance.
  • 15. Dependency Required ➢ If you are working with AEM6 then you have org.apache.sling.models.api package already present in your AEM instance. ➢ If you are using earlier version of AEM then you have to download this package from Sling website and then install it at your AEM instance. ➢ You can find all the Sling Models Injectors at http://localhost:4502/system/console/status-slingmodels
  • 16. Dependency Required ➢ If you are working with AEM6 then you have org.apache.sling.models.api package already present in your AEM instance. ➢ If you are using earlier version of AEM then you have to download this package from Sling website and then install it at your AEM instance. ➢ You can find all the Sling Models Injectors at http://localhost:4502/system/console/status-slingmodels ➢ Maven dependecy for your project can be found at-
  • 17. Dependency Required ➢ It depends on your AEM version so best way is to find this dependency at your on AEM instance for that you can search for – org.apache.sling.models in felix console bundles tab. Or ➢ Go to Felix Console packages tab And search for org.apache.sling.models.annotations.Model it you will get the Maven dependency for your project.
  • 18. Dependency Required ➢ It depends on your AEM version so best way is to find this dependency at your on AEM instance for that you can search for – org.apache.sling.models in felix console bundles tab. Or ➢ Go to Felix Console packages tab And search for org.apache.sling.models.annotations.Model it you will get the Maven dependency for your project. <dependency> <groupId>org.apache.sling</groupId> <artifactId>org.apache.sling.models.api</artifactId> <version>1.0.0</version> <scope>provided</scope> </dependency>
  • 19. ➢ Now add this dependency to your project. ➢ Search for maven-scr-plugin in your parent pom.xml file. ➢ Update it with <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Sling-Model-Packages> sling.models </Sling-Model-Packages> <Bundle-Category>sling-model-demo</Bundle-Category> </instructions> </configuration> </plugin> ➢ This plugin modification is mandatory so that this header must be added to the bundle's manifest file.
  • 20. Agenda 1. What are Sling Models? 2. Why Sling Models? 3. How to use Sling Models in AEM? 4. Sling Model annotations with Demo
  • 22. Before starting with these annotations, Let's have a look on this line of code. resource.adaptTo(ValueMap.class); In this code snippet - ➢ resource will behaves as an adaptable ➢ ValueMap behaves as an adapter
  • 23. Code Snippet Part - I @Model(adaptables = Resource.class ) public class ResourceValues { ... }
  • 24. Code Snippet Part - I @Model(adaptables = Resource.class ) public class ResourceValues { @Inject // If defined then Resource must have this property else it will return null. private String firstName; }
  • 25. Code Snippet Part - I @Model(adaptables = Resource.class ) public class ResourceValues { @Inject // If defined then Resource must have this property else it will return null. private String firstName; /* To provide default value to this string for Strings & primitives, Default only works with @Inject annotation not with @Optional annotation. */ @Inject @Default(values="defaultValue") private String lastName; }
  • 26. Code Snippet Part - I @Model(adaptables = Resource.class ) public class ResourceValues { @Inject // If defined then Resource must have this property else it will return null. private String firstName; /* To provide default value to this string for Strings & primitives, Default only works with @Inject annotation not with @Optional annotation. */ @Inject @Default(values="defaultValue") private String lastName; /* If the field or method name doesn't exactly match the property name */ @Inject @Named("secondPropertyName") private String otherName; }
  • 27. Code Snippet Part - I @Model(adaptables = Resource.class ) public class ResourceValues { @Inject // If defined then Resource must have this property else it will return null. private String firstName; /* To provide default value to this string for Strings & primitives, Default only works with @Inject annotation not with @Optional annotation. */ @Inject @Default(values="defaultValue") private String lastName; /* If the field or method name doesn't exactly match the property name */ @Inject @Named("secondPropertyName") private String otherName; @Optional // If defined then Resource may or may not have property. private String fullName; }
  • 28. Question? Is it required to add this @optional annotation at every field, if want to make is optional?
  • 29. Answer ? Yes, if you are using Sling API version before 1.0.2 and after this version you get another property in @Model annotation named as defaultInjectionStrategy. After adding this property all the fields are by default @optional. But if you wnat some field as required then you have to add @required annotation on that field. This property is defined in @Model annotation and it's syntex is- @Model(adaptables=Resource.class,defaultInjectionStrategy=DefaultInjectionStrategy.OPTIONAL)
  • 30. Code Snippet Part - II How to use Sling Models in AEM? ResourceValues resourceValues = resource.adaptTo(ResourceValues.class)
  • 31. Code Snippet Part - II How to use Sling Models in AEM? ResourceValues resourceValues = resource.adaptTo(ResourceValues.class) How to use in JSP? <sling:adaptTo adaptable="${resource}" adaptTo="org.apache.sling.models.it.models.MyModel" var="model"/>
  • 32. Code Snippet Part - II How to use Sling Models in AEM? ResourceValues resourceValues = resource.adaptTo(ResourceValues.class) How to use in JSP? <sling:adaptTo adaptable="${resource}" adaptTo="org.apache.sling.models.it.models.MyModel" var="model"/> How to use in Sightly? ${sling:adaptTo(resource, 'org.apache.sling.models.it.models.MyModel')}
  • 33. Code Snippet Part - III @Model(adaptables = Resource.class) public class ResourceValues { /* Child List injection works after Sling version 1.0.6. This List injection will hold list of all the child nodes present under childs node under current resource. */ @Inject private List<Resource> childs; }
  • 34. Code Snippet Part - III @Model(adaptables = Resource.class) public class ResourceValues { /* Child List injection works after Sling version 1.0.6. This List injection will hold list of all the child nodes present under childs node under current resource. */ @Inject private List<Resource> childs; /* The @PostConstruct annotation can be used to add methods which are invoked upon completion of all injections */ @PostConstruct protected void sayHello() { System.out.println("post construct is working"); } }
  • 35. Code Snippet Part - IV @Model(adaptables=SlingHttpServletRequest.class) public interface RequestValues { /* will return request.getResource().adaptTo(ValueMap.class).get("propertyName", String.class) */ @Inject @Via("resource") String getPropertyName(); } Means:- “If the injection should be based on a JavaBean property of the adaptable, you can indicate this using the @Via annotation”
  • 36. Code Snippet Part - V @Model(adaptables=SlingHttpServletRequest.class) public interface RequestValues { /* Ensure that "resource" is retrived from the bindings, not a request attribute */ @Inject @Source("script-bindings") Resource getResource(); }