A common use-case is configuring a path to a page via a dialog and then fetch the wrapper Page
object to retrieve information about that page. And there is a really easy way to do so.
The Cumbersome way
Sling models can have a method annotated with the @PostConstruct
annotation. This method is called after the sling model has been created and is used to initialise whatever fields you have defined. It looks typically like this for a page:
// @model annotation
public class PageSummary {
@Inject
private string articlePath; // this is a property in the dialog
@Service
private PageManager pageManager;
private Page page;
@PostConstruct
public void init(){
page = pageManager.getPage(articlePath);
}
}
The short way
Somewhere mentioned at the bottom of the sling model documentation page, you have @ResourcePath
. As stated in the docs:
Injects a resource either by path or by reading a property with the given name.
All examples you find online use this annotation on a field of type Resource
. But what you don’t see in these examples and is not stated literally in the docs: a Page
is a resource as well, so you can use this annotation on Page
fields. So the snippet above transforms to:
// @model annotation
public class PageSummary {
@ResourcePath(name="articlePath")
private Page page;
}
So no need to inject the dialog property, no PageManager
wiring and no @PostConstruct
annotated method!