5

我正在学习使用 AEM6 的一项新功能 - Sling Models。我已经按照此处描述的步骤获取了节点的属性

@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.

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

如果注入的对象与所需的类型不匹配,并且该对象实现了 Adaptable 接口,Sling Models 将尝试对其进行适配。这提供了创建丰富的对象图的能力。例如:

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

  @Inject
  ImageModel getImage();
}

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

  @Inject
  String getPath();
}

当资源适应 时MyModel,名为 image 的子资源会自动适应 的实例ImageModel

但我不知道如何在我自己的课程中实现它。这个你能帮我吗。

4

1 回答 1

4

听起来您需要一个单独的类来UserAddress包装houseNocity和属性。statelocality

+ 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课程中使用此模型:

@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 模型,但我也使用基于适配器工厂的遗留类来完成它。

于 2015-08-23T20:36:53.240 回答