通过 Sling Model 注释获取 Page 对象的正确方法是什么

What is the right way to get Page object via Sling Model annotation

我有一个属性内容文件中包含所需页面的路径

...
<some_block
    ...
    sling:resourceType="some_path_to_some_component"
    somePage="some_path_to_page"
    .../>
...

合适的HTL组件一些-component.html

<div data-sly-use.some_model="org.example.SomeModel">
    ...    
</div>

和型号classSomeModel.java

package org.example;
...
import com.day.cq.wcm.api.Page;
...

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

    @ValueMapValue
    private Page somePage;

    ...
}

我可以使用 @Inject and @Via annotations, but why can't I grab it with the @ValueMapValue annotation? I tried to use all the possible variants including via attribute and so on. And yes, I can get it from the pageManager, but what's wrong with @ValueMapValue?

轻松获得所需的页面对象

提前致谢!

您链接的 @ValueMapValue 注释文档有您要查找的答案:

Annotation to be used on either methods, fields or constructor parameter to let Sling Models inject a value from the ValueMap of the current resource.

重要的部分是:

inject a value from the ValueMap

A Page 不是 ValueMap。因此,此注解不能用于注入页面。

这个注解主要用来注入页面属性。因为页面属性(或与此相关的资源属性)存储在 ValueMap 中。这就是为什么您可以使用 @ValueMapValue 注释来注入页面的 jcr:title

@ValueMapValue(name = "jcr:title")
private String title;

这相当于(伪代码):

final ValueMap pageProperites = Page.getProperties();
final String title = pageProperties.get("jcr:title", "" /* default */);