如何在aem6的吊索模型中调整子节点

时间:2015-06-10 16:28:30

标签: cq5 aem sling-models

我正在学习使用AEM6的新功能之一 - Sling Models。我已经按照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

的属性

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

  

如果注入的对象与所需的类型不匹配,并且对象实现了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的实例。

但我不知道如何在我自己的课程中实现它。请帮帮我。

1 个答案:

答案 0 :(得分:4)

听起来你需要一个单独的类来UserAddress包装houseNocitystatelocality属性。

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

只需反映您在Sling Models中列出的结构。

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