Sling Models - bartoszWesolowski/aem-tips GitHub Wiki

Sling models

  • java classes that can be injected into a HTML code
  • used to implement custom business logic (separates logic from presentation)
  • OOTB works with OSGi services, request attributes
  • simplifies extracting data from the JCR resource

This header must be added to bundle manifest (all sling model under this package, including sub packages, will be scanned):

<Sling-Model-Packages>
  org.apache.sling.models.it.models
</Sling-Model-Packages>

It can also be comma separated list of packages.

Instantiating a Sling Model

Adapting Sling models supports adapter framework. Sling model can be adapted from Resource and/or Request depending on definition.

resource.adaptTo(MyModel.class)

Model factory (since 1.2.0)#

try {
    MyModel model = modelFactory.createModel(object, MyModel.class);
} catch (Exception e) {
    // give out error message that the model could not be instantiated. 
    // The exception contains further information. 
    // See the javadoc of the ModelFactory for which Exception can be expected here
}

Injecting fields

  • by default all fields are required (if required argument is missing then model will not be created)
  • To mark property as optional @Optional annotation can be used
  • Sling model also supports injection strategy to mark all fields as required (default), or optional.
  • Supports injecting OSGi services
//other option (default): defaultInjectionStrategy = DefaultInjectionStrategy.REQUIRED
@Model(adaptables=Resource.class, defaultInjectionStrategy=DefaultInjectionStrategy.OPTIONAL)
public class MyModel {

    // OSGi serivice    
    @Inject
    private ResourceResolverFactory resourceResolverFactory;

    // Majority of optional parametrs
    @Inject
    private String optionalProp;

    @Inject
    @Required //use only when strategy is optional
    private String required;
   
    @Inject
    private List<Resource> addresses; //child node named addresses with children that will be injected to this list

    @PostConstruct
    protected void sayHello() {
         // use this method to configure model after injecting all the fields
    }
}

Alternative adapter class

  • allows to adapt to a multiple classes/interfaces Example: Resource that can be adapted to MyService interface:
@Model(adaptables = Resource.class, adapters = MyService.class)
public class MyModel implements MyService { ... }

Model Exporter

  • allows to export a resource to JSON (OOTB), or any data type (custom development needed)
  • create a servlet that will handle all requests with .model selector for registered resource type
  • model mapped to resource type
  • @Exporter annotation (json exporter available OOTB)
  • can be used for SPA

Documentation

⚠️ **GitHub.com Fallback** ⚠️