Aem 无法将模型类改编为SlingHttpServletRequest

Aem 无法将模型类改编为SlingHttpServletRequest,aem,sling-models,Aem,Sling Models,我试图在我的模型类中注入资源。当我使用注解@Model(adapteables={SlingHttpServletRequest.class,Resource.class})时遇到的问题 我将对象获取为null,而仅使用Resource.Class我将获取对象(navigationItems)。下面是我的课程片段。你能告诉我修理它的步骤吗 import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.ap

我试图在我的模型类中注入资源。当我使用注解
@Model(adapteables={SlingHttpServletRequest.class,Resource.class})时遇到的问题

我将对象获取为null,而仅使用Resource.Class我将获取对象(navigationItems)。下面是我的课程片段。你能告诉我修理它的步骤吗

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;

@Model(adaptables =  { SlingHttpServletRequest.class, Resource.class })
public class Header {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Inject
    @Optional
    @Named("navitems")
    private Resource navigationItems;

    List<SiteNavigation> siteNavigationList;

    @PostConstruct
    protected void init() {
        logger.info("In init method of header model.");
        siteNavigationList = getSiteNavigationListItems(getNavigationItems());
    }

    private List<SiteNavigation> getSiteNavigationListItems(final Resource navigationItems, final Resource columnFourItems) {
        return null;
    }

    public Resource getNavigationItems() {
        return navigationItems;
    }
}

此问题通过@Via注释解决。下面是我使用的代码片段

@Inject
    @Via("resource")
    @Named("navitems")
    private Resource navigationItems;

代码中有3个指针:

  • 虽然sling9支持多个适配器,但最好是SlingHttpServetRequest对象。它位于更高的层,并包裹大多数其他对象
  • 建议将您的注入器设置为比通用@Inject更多的注入器
  • 始终指定将模型与特定资源类型关联。有利于碎片的导出,sling关联更紧密,可读性更好 这将是我对您的吊索型号的代码:

    @Model(adaptables = SlingHttpServletRequest.class, resourceType = "myprj/components/content/header",
      defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
    public class Header {
    
      @ChildResource
      private Resource navitems; // Keeping resource name and attribute name identical reduces @Named annotation
    

    request.getResource()
    是否提供了错误的资源?添加了
    @Inject-SlingHttpServletRequest请求request.getResource()
    中的code>为我提供了正确的节点路径,该节点是头节点<代码>/conf/myprj/settings/wcm/templates/homepage/structure/jcr:content/root/header
    @Model(adaptables = SlingHttpServletRequest.class, resourceType = "myprj/components/content/header",
      defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
    public class Header {
    
      @ChildResource
      private Resource navitems; // Keeping resource name and attribute name identical reduces @Named annotation