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

Man*_*sha 5 aem sling-models

我正在学习使用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;
  }
}
Run Code Online (Sandbox Code Playgroud)

并从资源中调整它

UserInfo userInfo = resource.adaptTo(UserInfo.class);
Run Code Online (Sandbox Code Playgroud)

现在我的等级为 -

+ UserInfo (firstName, lastName, technology)
  |
  + UserAddress (houseNo, locality, city, state)
Run Code Online (Sandbox Code Playgroud)

现在我想获取的属性UserAddress.

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

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

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

  @Inject
  ImageModel getImage();
}

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

  @Inject
  String getPath();
}
Run Code Online (Sandbox Code Playgroud)

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

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

ton*_*edz 4

听起来您需要一个单独的类来UserAddress包装houseNocitystate属性locality

+ UserInfo (firstName, lastName, technology)
  |
  + UserAddress (houseNo, locality, city, state)
Run Code Online (Sandbox Code Playgroud)

只需镜像您在吊索模型中概述的结构即可。

创建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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

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

一般来说,Sling 模型应该能够处理另一个模型的注入,只要它找到合适的适应性。在本例中,它是另一个 Sling 模型,但我也使用基于适配器工厂的遗留类来完成它。