如何适应aem6吊索模型中的子节点
我正在学习使用AEM6-Sling机型的一个新功能。我已经按照描述的步骤获取了节点的属性 并根据资源进行了改编如何适应aem6吊索模型中的子节点,aem,sling-models,Aem,Sling Models,我正在学习使用AEM6-Sling机型的一个新功能。我已经按照描述的步骤获取了节点的属性 并根据资源进行了改编 UserInfo userInfo = resource.adaptTo(UserInfo.class); 现在我的层次结构是- + UserInfo (firstName, lastName, technology) | + UserAddress (houseNo, locality, city, state) 现在我想获取UserAddress的属性 我从文档页面上得
UserInfo userInfo = resource.adaptTo(UserInfo.class);
现在我的层次结构是-
+ UserInfo (firstName, lastName, technology)
|
+ UserAddress (houseNo, locality, city, state)
现在我想获取UserAddress
的属性
我从文档页面上得到了一些提示,例如-
如果注入的对象与所需的类型不匹配,并且该对象实现了自适应接口,吊索模型将尝试对其进行自适应。这提供了创建丰富对象图的能力。例如:
当资源被改编为MyModel
时,名为image的子资源将自动改编为ImageModel
的实例
但是我不知道如何在我自己的类中实现它。请帮我解决这个问题。听起来您需要为
用户地址
单独设置一个类来包装房屋号
、城市
、州
和地区
属性
+ UserInfo (firstName, lastName, technology)
|
+ UserAddress (houseNo, locality, city, state)
只需镜像您在吊索模型中概述的结构即可
创建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模型,但我也使用了基于适配器工厂的遗留类
@Model(adaptables = Resource.class)
public class UserAddress {
@Inject
private String houseNo;
@Inject
private String locality;
@Inject
private String city;
@Inject
private String state;
//getters
}
@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
}