@yaminikolhe
Great question—this touches on a subtle but important aspect of how Sling Models resolve dependencies using annotations like @Model and @Self.
Purpose of @Model(adaptables = { ... })
@Model(adaptables = { Resource.class, SlingHttpServletRequest.class })
You're telling Sling Models that this class can be instantiated (adapted) from either a Resource or a SlingHttpServletRequest
So when code like this runs:
modelFactory.getModelFromWrappedRequest(request, MyModel.class);
or
resource.adaptTo(MyModel.class);
It will look for a matching adaptable type and attempt to inject the model.
What does @Self mean then?
The @Self annotation is used on fields or constructor parameters inside the model to inject the same object that was used to adapt the model.
For ex:
@Self
private Resource resource;
Here’s what this does:
- If the model was adapted from a Resource, resource will be injected with that same Resource.
- If the model was adapted from a SlingHttpServletRequest, the framework will try to get a Resource from the request (i.e., request.getResource()) and inject that.
Hope this is clear