Search code examples
aemsling

Sling resource.getResourceResolver() Vs SlingHttpRequest.getResourceResolver


In my project I am seeing in Sling model classes, the resource resolver is fetched in 2 ways

@Inject private Resource resource;
ResourceResolver resolver = resource.getResourceResolver();

Vs

@Inject @Self private SlingHttpServletRequest request;
ResourceResolver resolver = request.getResourceResolver();

While both are Sling implementations, is there any benefit of using one opposed other? Or are these 2 yield same resolver with no performance difference?


Solution

  • Resource#getResourceResolver returns the ResourceResolver with which the resource was retrieved from the repository. This retrieval will often happen in association with a request but that doesn't have to be the case.

    SlingHttpServletRequest#getResourceResolver returns the ResourceResolver with which the requested resource was retrieved.

    These resource resolvers may be the same but it depends on the way your Sling Model is instantiated.

    For example, imagine an OSGi Service that is not directly associated with a request. It could be an event handler of some sort that executes once in a while and loads some resources. It could, for example, retrieve a ResourceResolver using a ResourceResolverFactory and a service-user mapping.

    ResourceResolver serviceResourceResolver = resourceResolverFactory.getServiceResourceResolver(authenticationInfo);
    Resource someResource = serviceResourceResolver.getResource("/path/to/resource");
    someResource.adaptTo(MyModel.class);
    

    In this case, you will not be able to inject a SlingHttpSerlvetRequest object so this will fail:

    @Inject
    @Self
    private SlingHttpServletRequest request;
    

    Generally speaking, there is, therefore, a difference in semantics.

    If we look at the simple case where the resource you're adapting was retrieved in scope of a request, the following two ResourceResolver instances should be equivalent:

    @Inject private Resource resource;
    ResourceResolver resolver = resource.getResourceResolver();
    

    and

    @Inject @Self private SlingHttpServletRequest request;
    ResourceResolver resolver = request.getResourceResolver();
    

    The resolvers will have the same permissions as the user making the request.

    When it comes to performance, I'm not aware of any documentation recommending one approach or the other.