Back
2

Resource Resolvers in AEM with ResourceResolverFactory

Tags:JavaAEM
May 21, 2021

In this post, I share sample code to get a Sling ResourceResolver in AEM using the ResourceResolverFactory getServiceResourceResolver method. 

For additional context, review the documentation on the Sling ResourceResolverFactory.

Create the Service

The code below assumes that you have created the WriteService interface and defined a service user with appropriate permissions for your needs (Review the RepoInit post if you have not already).

package com.tutorials.aem.core.services.impl;

import com.tutorials.aem.core.services.WriteService;
import java.util.HashMap;
import java.util.Map;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

@Component(immediate = true, service = WriteService.class)
public class WriteServiceImpl implements WriteService {

    @Reference
    ResourceResolverFactory resolverFactory;

    @Override
    public ResourceResolver getResourceResolverObject() throws LoginException {
        Map<String, Object> param = new HashMap<>();
        param.put(ResourceResolverFactory.SUBSERVICE, "WriteService");
        ResourceResolver resolver;

        resolver = resolverFactory.getServiceResourceResolver(param);
        return resolver;
    }
}

 

The WriteService can be imported and used to retrieve the Resource Resolver in other classes.

ResourceResolver resolver = writeService.getResourceResolverObject();

 

Remember to close the resolver when your work is done.

resolver.close();