Can anyone explain to me the difference between calling resourceResolver
by annotating @ScriptVariable
and by annotating @SlingObject
? In what context do they behave differently?

- 17,895
- 9
- 86
- 131

- 41
- 5
1 Answers
The key difference is in the way the object is retrieved. @ScriptVariable
and @SlingObject
are injector-specific annotations. This means that you can use them to instruct Sling Models to use a particular injector.
The injector that recognises the @ScriptVariable
annotation can inject objects available as Scripting Variables. In case ot the resourceResolver
, it should be the one associated with the request. Same as slingRequest.getResourceResolver()
.
Looking at the code, the injector that kicks in on fields annotated with @SlingObject
is a bit more interesting in that it will inspect the adaptable (from which your Sling Model is being adapted) and obtain the resolver accordingly:
- If the adaptable is a
Resource
, it'll returnresource.getResourceResolver()
, i.e. the resolver originally used to load the resource. This may be quite aribtrary. - If the adaptable is a
SlingHttpServletRequest
, it'll returnrequest.getResourceResolver()
, i.e. the resolver instantiated by Sling in association with the request and the session of the user issuing the request. - If the adaptable itself is a
ResourceResolver
, it will be returned directly.
In some cases, the difference between the three will be negligible, but sometimes it will be important which resolver you choose. If your model is, for example, supposed to be used outside the scope of a request (imagine it's instantiated by an OSGi service that runs on a schedule and there's no incoming request), you'll be better off using resource
or resourceResolver
as an adaptable.

- 17,895
- 9
- 86
- 131