Creating a Sling Model
- @Model: declares a bean as Sling Model.
- @Inject: Injects resource property into a class variable.
- @PostConstruct: declares the function which would initialize the bean after deriving information based on business logic. The function is called after the all injections have completed.
- In the above example, ‘adaptables = Resource.class’ maps the sling model against a Sling Resource.
- The @Inject would inject ‘contacts’ property from the resource into ‘contacts’ class variable. The property value injection occurs after adapting the Resource into Value Map.
@Model annotation provides ‘defaultInjectionStrategy’ attribute to indicate if the injected fields in a sling model should be required/optional.
Injection strategy on class level:
- Use ‘defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL’ to mark all injected fields as optional
- Use ‘defaultInjectionStrategy = DefaultInjectionStrategy.REQUIRED’ to mark all injected fields as required. Its also the default configuration, if ‘defaultInjectionStrategy’ is not specified.
Injection strategy on Field level:
- @Required / @Optional annotations can be used to selectively mark fields as required/optional.
Adapt Model from Resource / SlingHttpServletRequest
A Models can be adapted both Resource / SlingHttpServletRequest. This depends upon the fields required to be injected.
- If only resource properties are required, prefer using:
- If Sling Objects (eg. currentStyle, currentPage, xssApi etc) are also required, prefer adapting to SlingHttpServletRequest.
Refer to link, to use attribute names matching with the field’s type.
Alternate field name
Use @Named if the field name is different from the property name.
The Design object can be accessed on adapting model to Resource / SlingHttpServletRequest
Injecting currentStyle object
Used when the Sling Model is adapted from SlingHttpServletRequest. Example:
Fetch currentStyle object from Resource
Used when the Sling Model is adapted from Resource. Example:
Inject OSGi Services
OSGi services can be injected via @Inject. The annotation could be used while adapting to both Resource and SlingHttpServletRequest