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

Dmi*_*lko 0 sling aem sightly htl

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

...
<some_block
    ...
    sling:resourceType="some_path_to_some_component"
    somePage="some_path_to_page"
    .../>
...
Run Code Online (Sandbox Code Playgroud)

合适的HTL组件some-component.html

<div data-sly-use.some_model="org.example.SomeModel">
    ...    
</div>
Run Code Online (Sandbox Code Playgroud)

和模型类SomeModel.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;

    ...
}
Run Code Online (Sandbox Code Playgroud)

我可以轻松地获得使用所需的Page对象@Inject@Via注释,但为什么我不能用抢吧@ValueMapValue注解?我试图使用所有可能的变体,包括via属性等.是的,我可以从pageManager获取它,但@ValueMapValue有什么问题?

提前致谢!

Jen*_*ens 5

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

要在方法,字段或构造函数参数上使用的注释,以使Sling模型从当前资源的ValueMap中注入值.

重要的是:

从ValueMap注入一个值

A Page不是ValueMap.因此,此注释不能用于注入页面.

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

@ValueMapValue(name = "jcr:title")
private String title;
Run Code Online (Sandbox Code Playgroud)

这相当于(伪代码):

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