ResourceResolverFactory为NULL(Adobe Experience Manager AEM)

时间:2014-11-18 23:10:28

标签: java aem

我试图从ResourceResolverFactory获取对ResourceResolver的引用,如下所示:

@Reference
private ResourceResolverFactory resourceResolverFactory;

public void someMethod() {
    Map<String, Object> authenticationMap = new HashMap<String, Object>();
        authenticationMap.put(ResourceResolverFactory.USER, "user");
        authenticationMap.put(ResourceResolverFactory.PASSWORD, "pwd");

        //This line returns NullPointerException
        ResourceResolver resourceResolver =   resourceResolverFactory.getResourceResolver(authenticationMap); 
}

有人可以告诉我我做错了什么吗? AEM API版本v6.0。

1 个答案:

答案 0 :(得分:4)

所以我做的是创建一个在部署和启动bundle时调用的Activator类。然后,Activator类获取org.apache.sling.jcr.api.SlingRepository的实例,我们可以使用它来连接到JCR。这是激活码:

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate = true, label = "Commons Activator")
public class Activator implements BundleActivator { 

@Reference
private SlingRepository repository;

private static final Logger logger = LoggerFactory.getLogger(Activator.class);

@Activate
@Override
public void start(BundleContext context) throws Exception {
    logger.info(context.getBundle().getSymbolicName() + " started");

    //My own factory class instance
    ResourceResolverDiscoveryService rrf = ResourceResolverDiscoveryService.getInstance();
    //Set the 'repository' in your factory class instance
    rrf.setSlingRepositoryFactory(repository);
}

@Deactivate
@Override
public void stop(BundleContext context) throws Exception {
    logger.info(context.getBundle().getSymbolicName() + " stopped");
}

}

然后在我想使用JCR存储数据的类中,我执行了以下操作:

public class StoreInJCR {
  public void store(Quote quote) throws LoginException, RepositoryException {
        SlingRepository slingRepository = ResourceResolverDiscoveryService.getInstance().getSlingRepositoryFactory();

        // GOT IT!!! Mission Accomplished
        Session session = slingRepository.loginAdministrative(null);
        Node root = session.getRootNode();
        // Further code
        .
        .
  }
}

希望有人觉得这很有用。