This blog post is based on an issue encountered on a project I’ve worked on. I’ve been working with AEM for a while and in that time I wrote my share of Sling models and unit tests for them. Reading through lots of references on the internet explaining which annotations you can use and how they work. Also using some third-party custom annotations and even adding a custom annotation myself to be used in Sling models.
Yet all this time, the way Sling models work their magic stayed magical somehow... Especially the mysterious @Inject annotation. However, I never encountered really weird behaviour that couldn’t be accounted for one way or another. Until recently.
Before presenting the issue I want to indicate what DOES work.
In an OOTB AEM instance, the Sling model based on the SlingHttpServletRequest works and injects the current page fine, however, the one based on the Resource does not work!
This makes a lot of sense since the current page is present on the request in the sling bindings which can be obtained from the attributes. However, the resource doesn’t keep a reference to the current page nor request. Note: the current page is different from the containing page. It is possible to get the containing page for a resource.