Skip to main content

Sling Models in AEM - Complete Guide

Updated 9 min readMarkdown
Part of seriesApache Sling Series

When building AEM components, you often need to map repository content (nodes, properties) to Java objects. This is where Sling Models come in, they simplify and standardize this mapping, providing a clean, type-safe way to work with content in your Java code.

What Are Sling Models?

  • Sling Models are POJOs annotated with Sling annotations that map properties from a Resource, Request, or other adaptable objects.

  • They act as a bridge between the JCR repository and the front-end.

  • Introduced to reduce boilerplate code compared to traditional SlingHttpServletRequest or Resource handling in Servlets.


Sling Model Adaptables: What You Can Adapt From and When

In Sling Models, the @Model annotation has a property called adaptables. It defines the types of objects your model can be adapted from. In simple terms: what is the “starting point” for creating your model instance.

@Model(adaptables = {Resource.class, SlingHttpServletRequest.class})
public class MyModel { ... }

Here, Resource.class and SlingHttpServletRequest.class are adaptables.


1. Resource

  • Type: org.apache.sling.api.resource.Resource

  • When to use:

    • Most common adaptable in AEM components.

    • Use when your model is primarily backed by JCR content (properties, child nodes, metadata).

  • What you can inject:

    • @ValueMapValue properties

    • OSGi services (@OSGiService)

    • Other resources (@Self Resource resource)

  • Example:

@Model(adaptables = Resource.class)
public class MyComponentModel {

    @ValueMapValue
    private String title;

    @Self
    private Resource resource;
}
  • Use case: Component backed by /content/... nodes, want access to properties and resource tree.

2. SlingHttpServletRequest

  • Type: org.apache.sling.api.SlingHttpServletRequest

  • When to use:

    • You need request-specific context (request parameters, selectors, headers, request attributes, session).

    • Enables access to both resource and request context.

  • What you can inject:

    • Same as Resource, plus request-related info:

      • @RequestParameter

      • @ScriptVariable (Sling/HTL variables)

      • @Self SlingHttpServletRequest request

  • Example:

@Model(adaptables = SlingHttpServletRequest.class)
public class MyComponentModel {

    @Inject @Optional
    private String pageTitle;

    @Self
    private SlingHttpServletRequest request;

    public String getSelector() {
        return request.getRequestPathInfo().getSelectorString();
    }
}
  • Use case: When behavior depends on current request, such as selectors or query parameters.

3. Resource + SlingHttpServletRequest

  • Type: Both together.

  • When to use:

    • Most flexible.

    • You can adapt from a resource when the model is instantiated from a request context.

  • Example:

@Model(adaptables = {Resource.class, SlingHttpServletRequest.class})
public class MyComponentModel {

    @Inject
    @Optional
    private String title;

    @Self
    private Resource resource;

    @Self
    private SlingHttpServletRequest request;
}
  • Use case: Components rendered via HTL or servlets where both request and resource are needed.

defaultInjectionStrategy in Sling Models

The defaultInjectionStrategy is a property of the @Model annotation. It sets the default behavior for all injection points in your model, unless you override it at a specific field level.

@Model(
    adaptables = Resource.class,
    defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL
)
public class MyModel {

    @Inject
    private String title;

    @Inject
    private MyService myService;
}

Here, all injection points are optional by default.


Available Strategies

1. REQUIRED (Default if not specified)

  • Behavior:

    • Injection must succeed.

    • If the adaptable cannot provide a value, Sling Models throws a ModelClassException at adaptation time.

  • Use case:

    • When a property/service is mandatory for the model to function.
  • Example:

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.REQUIRED)
public class MyModel {
    @Inject
    private String title; // Must exist, otherwise adaptation fails
}

2. OPTIONAL

  • Behavior:

    • Injection is not mandatory.

    • If the adaptable cannot provide a value, the field is left null (or default for primitive types).

    • No exception is thrown.

  • Use case:

    • For optional properties or services that are not critical.
  • Example:

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class MyModel {
    @Inject
    private String title; // If property missing, title = null
}

3. Field-Level Override

Even if defaultInjectionStrategy is set at the class level, you can override it per field using the injectionStrategy property:

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class MyModel {

    @Inject
    private String description; // Optional

    @Inject(injectionStrategy = InjectionStrategy.REQUIRED)
    private String title; // Mandatory
}
  • title must be injected successfully.

  • description can be null.


@Exporter Annotation

@Exporter allows a Sling Model to be serialized into JSON or other formats automatically. It makes your model directly consumable by frontends without writing custom serialization code.

Think of it as the bridge between Java model objects and API-ready data.

Key Properties

Property Description Example
name The name of the exporter. Usually "jackson" for JSON. @Exporter(name="jackson")
extensions The file extension(s) used to request this export via HTTP. extensions="json"
selector Optional Sling selector to differentiate exports. @Exporter(name="jackson", selector="data")
options Map of key-value pairs for additional exporter options. @Exporter(name="jackson", extensions="json", options = { @ExporterOption(name="SerializationFeature.INDENT_OUTPUT", value="true") })

Example: Basic JSON Export

@Model(adaptables = Resource.class)
@Exporter(name = "jackson", extensions = "json")
public class TeaserModel {

    @ValueMapValue
    private String title;

    @ValueMapValue
    private String description;

    @ValueMapValue
    private String imagePath;

    // Getters
    public String getTitle() { return title; }
    public String getDescription() { return description; }
    public String getImagePath() { return imagePath; }
}

Access via HTTP:

/content/site/en/teaser.component.json

Output:

{
  "title": "Welcome to AEM",
  "description": "AEM is awesome!",
  "imagePath": "/content/dam/site/images/banner.jpg"
}

Now that we’ve explored class-level annotations like @Model and @Exporter along with their key properties, it’s time to dive into field- and method-level annotations. These annotations control how individual model properties are injected, processed, and exposed, giving your Sling Models their dynamic behavior and flexibility.


1. @Inject

The core injection annotation. Marks a field or method for injection.

Properties / Features:

  • optional: true or false (default false) - indicates whether injection failure should be ignored.

  • Supports injection from multiple adaptables: resource, request, or adaptable context.

When to Use:

  • Generic injection from any adaptable.

  • Often used as a default if you don’t need specialized behavior.

Example:

@Inject
private String title;

2. @ValueMapValue

Injects values directly from a resource’s ValueMap.

Properties / Features:

  • name: Name of the property in the repository (if different from field name).

  • injectionStrategy: REQUIRED or OPTIONAL - what to do if the value is missing.

When to Use:

  • Injecting properties from a resource node in JCR.

  • Common for component dialog properties in AEM.

Example:

@ValueMapValue(name = "jcr:title", injectionStrategy = InjectionStrategy.OPTIONAL)
private String title;

3. @OSGiService

Injects an OSGi service into the model.

Properties / Features:

  • name: Optional service name if multiple implementations exist.

  • filter: OSGi filter to select a specific service.

  • injectionStrategy: REQUIRED / OPTIONAL

When to Use:

  • Injecting reusable services like ResourceResolverFactory, PageManager, or custom services.

Example:

@OSGiService
private ResourceResolverFactory resolverFactory;

4. @Self

Injects the adaptable itself into the model.

Properties / Features:

  • Typically used when you need the full adaptable object: Resource, SlingHttpServletRequest, or another model.

When to Use:

  • When the model needs access to the parent adaptable or context object (which used at class level).

Example:

@Self
private Resource resource;

5. @Default

Provides a default value if injection fails or the property is missing.

Properties / Features:

  • stringValue: Default string value

  • boolValue / intValue / longValue: For typed defaults

Example:

@ValueMapValue(injectionStrategy = InjectionStrategy.OPTIONAL)
@Default(values = "Default Title")
private String title;

6. @PostConstruct

Marks a method to be called after all injections are complete.

When to Use:

  • Initialize computed fields or perform setup logic that depends on injected values.

Example:

@PostConstruct
protected void init() {
    this.fullTitle = title + " - " + subtitle;
}

9. @Via

Specifies the path to follow for injection, instead of direct injection from the adaptable.

Properties / Features:

  • type: Can be Resource, Request, etc.

  • value: Relative path to follow for injection.

When to Use:

  • To inject values from a nested resource or child node.

Example:

@ValueMapValue
@Via("parent")
private String parentTitle;

Example Scenario

Suppose you have the following content structure in AEM:

/content/mysite/jcr:content/root
 ├── title = "Homepage"
 └── teaser
      ├── heading = "Welcome"
      └── description = "This is the homepage teaser"
  • The model is adapted from the Resource at /content/mysite/jcr:content/root.

  • You want to inject heading and description which are inside the teaser child node.


Without @Via

You would have to do this manually:

@Model(adaptables = Resource.class)
public class PageModel {

    private String heading;
    private String description;

    public PageModel(Resource resource) {
        Resource teaser = resource.getChild("teaser");
        if (teaser != null) {
            heading = teaser.getValueMap().get("heading", String.class);
            description = teaser.getValueMap().get("description", String.class);
        }
    }

    public String getHeading() { return heading; }
    public String getDescription() { return description; }
}

✅ Works, but boilerplate code and less declarative.


With @Via

@Via lets you tell Sling Models to look at the teaser child node automatically.

@Model(adaptables = Resource.class)
public class PageModel {

    @ValueMapValue
    @Via("teaser")
    private String heading;

    @ValueMapValue
    @Via("teaser")
    private String description;

    public String getHeading() { return heading; }
    public String getDescription() { return description; }
}
  • @Via("teaser") tells Sling Models:

    Instead of reading directly from the adaptable resource, go through the teaser child node and get the property.

  • No constructor or manual code required.


How Sling Models Are Used in HTL

<div class="teaser">
    <h2>${model.title}</h2>
    <p>${model.description}</p>
</div>
  • model is automatically available if you use data-sly-use in HTL:
<sly data-sly-use.model="com.example.models.TeaserModel"></sly>
  • Makes templates clean and declarative, with minimal Java code in the front-end.

Why Use Sling Models?

  • Eliminates repetitive code for property extraction.

  • Encourages clean separation between backend logic and HTL.

  • Works seamlessly with AEM’s dependency injection and OSGi services.

  • Makes unit testing easier, as models are plain Java classes.


What’s Next?

In the next post, we’ll explore - Understanding ResourceResolver in Apache Sling: Accessing Content Safely and Efficiently.

No comments yet. Be the first to comment.