如何在aem6的sling模型中适配子节点

How to adapt a child node in sling model of aem6

我正在学习使用 AEM6 的一项新功能 - 吊索模型。我已经按照 here

中描述的步骤获取了节点的属性
@Model(adaptables = Resource.class)
public class UserInfo {

  @Inject @Named("jcr:title")
  private String title;

  @Inject @Default(values = "xyz")
  private String firstName;

  @Inject @Default(values = "xyz")
  private String lastName;

  @Inject @Default(values = "xyz")
  private String city;

  @Inject @Default(values = "aem")
  private String technology;

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public String getTechnology() {
    return technology;
  }

  public String getTitle() {
    return title;
  }
}

并根据资源进行改编

UserInfo userInfo = resource.adaptTo(UserInfo.class);

现在我的层次结构为 -

+ UserInfo (firstName, lastName, technology)
  |
  + UserAddress (houseNo, locality, city, state)

现在我想获取 UserAddress 的属性。

我从文档页面得到了一些提示,例如 -

If the injected object does not match the desired type and the object implements the Adaptable interface, Sling Models will try to adapt it. This provides the ability to create rich object graphs. For example:

@Model(adaptables = Resource.class)
public interface MyModel {

  @Inject
  ImageModel getImage();
}

@Model(adaptables = Resource.class)
public interface ImageModel {

  @Inject
  String getPath();
}

When a resource is adapted to MyModel, a child resource named image is automatically adapted to an instance of ImageModel.

但我不知道如何在我自己的 类 中实现它。请帮我解决这个问题。

听起来您需要一个单独的 class 用于 UserAddress 来包装 houseNocitystatelocality属性。

+ UserInfo (firstName, lastName, technology)
  |
  + UserAddress (houseNo, locality, city, state)

只需反映您在 Sling 模型中概述的结构。

创建 UserAddress 模型:

@Model(adaptables = Resource.class)
public class UserAddress {

    @Inject
    private String houseNo;

    @Inject
    private String locality;

    @Inject
    private String city;

    @Inject
    private String state;

    //getters
}

此模型可用于您的 UserInfo class:

@Model(adaptables = Resource.class)
public class UserInfo {

    /*
     * This assumes the hierarchy you described is 
     * mirrored in the content structure.
     * The resource you're adapting to UserInfo
     * is expected to have a child resource named
     * userAddress. The @Named annotation should
     * also work here if you need it for some reason.
     */
    @Inject
    @Optional
    private UserAddress userAddress;

    public UserAddress getUserAddress() {
        return this.userAddress;
    }

    //simple properties (Strings and built-in types) omitted for brevity
}

您可以使用默认值和可选字段的附加注释来调整行为,但这是一般的想法。

一般来说,Sling Models 应该能够处理另一个模型的注入,只要它找到合适的适应性。在这种情况下,它是另一个 Sling 模型,但我也使用基于适配器工厂的遗留 classes 完成了它。