AEM 吊索模型 - 为什么我们在每个模型中都需要未使用的适应性?为什么需要 Resource 和 SlingHTTPRequest?

the*_*ual 1 java sling aem sling-models

我正在开发一个项目,每个模型都有这一行:

@Model(adaptables = { SlingHttpServletRequest.class,Resource.class },
 defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
Run Code Online (Sandbox Code Playgroud)

以我的理解:

  1. 如果不使用 Resource 或 SlingHTTPRequest,则必须从模型中删除此依赖项注入
  2. 无论如何,SlingHTTPRequest 可以通过使用 .getResource 方法来帮助获取资源,因此单独使用 SlingHTTPServeltRequest 类,以及所需的 dependencyInjectionStrategy 应该足够了,并且永远不需要 Resource 类作为适应性?

请分享您的想法。提前致谢!

Ale*_*ndt 5

问题1)

  • SlingModel 必须从 SlingHttpServletRequest 或资源创建/改编。它不可能从无到有。

  • Adaptables-property 指定可以从哪个对象创建它。

  • 如果 SlingModel 可以从两者创建,则脚本环境(例如 HTL 脚本)将使用该资源。但 SlingModel 也可以在其他地方使用,因此来源是随机的。

提示 1:不要同时使用两种适配器。因此,要么选择 SlingHttpServletRequest,要么选择 Resource。因为两者都可以工作,但是注入会有所不同 - 并且可能会导致奇怪的错误(至少它是薄冰,并且很难测试)。@Self 的示例很简单,但其他一些注入器甚至更复杂,因为 @Via 隐式发生了变化。

@Model(adaptables = { SlingHttpServletRequest.class, Resource.class },
                      defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class MySlingModel {

@Self
// will be null, if adapted from Resource!!!
private SlingHttpServletRequest request;

@Self
// will be null, if adapted from SlingHttpServletRequest!!!
private Resource resource;
Run Code Online (Sandbox Code Playgroud)

问题2

组件(以及 SlingModels)应该是上下文无关的,并由资源(= JCR 节点和 evtl.一些子节点)表示。因此,SlingModel 通常应改编自资源。它也更容易在其他地方使用(在其他服务或吊带模型中)。

只是,如果您需要请求中的某些内容,请切换到 SlingHttpServletRequest。不幸的是,这通常是 URL 映射所必需的。但限制自己访问 RequestAttributes。即使是像 WcmMode 这样的东西也不应该在 SlingModel 中使用。最好将 SlingModel 视为资源的包装器,即用于访问数据的小型 Java 层。

提示 2:并非所有东西都是 SlingModel!您可以创建服务、Servlet、AdapterFactories、过滤器、重写器……