Reputation: 7078
One reason for my other question is the following use case: I want to create a TextImageModel which uses my ImageModel as an injected property and extends my TextModel:
@Model(adaptables = {SlingHttpServletRequest.class})
public class TextImageModel extends TextModel {
@Inject
private ImageModel image;
}
But this doesn't work. It should work when I would be using Resource
as the adaptable, but I need the SlingHttpServletRequest in my ImageModel and TextModel as well:
@Model(adaptables = {SlingHttpServletRequest.class})
public class ImageModel {
@SlingObject
private SlingHttpServletRequest request;
@SlingObject
private Resource resource;
}
How can I inject the ImageModel using the request as adaptable?
The image resource is a child resource with the name image
Upvotes: 0
Views: 2267
Reputation: 1176
Use the ModelFactory:
...
import com.adobe.cq.wcm.core.components.models.Image;
import org.apache.sling.models.factory.ModelFactory;
...
@Inject
private ModelFactory modelFactory;
@Self
private SlingHttpServletRequest request;
private Image image;
@PostConstruct
protected void postInit() {
image = modelFactory.getModelFromWrappedRequest(request, resource.getChild("image"), Image.class);
...
}
That should hopefully do the trick.
Upvotes: 3
Reputation: 346
You can use @Self instead of @Inject, but you will have the same resource in ImageModel as in TextImageModel. Not child "image" as you would like to. Afaik when adapting from Request, resource will be always read from Request.
@Model(adaptables = {SlingHttpServletRequest.class})
public class TextImageModel extends TextModel {
@Self
private ImageModel image;
}
Upvotes: 1
Reputation: 1674
If you want to inject from a specific other type than your adaptable then you can use @Inject @Via("resource")
more here: https://sling.apache.org/documentation/bundles/models.html#via
I'm not sure though whether that will work with a model and not a property
Upvotes: 0