How to access Configuration inside a servlet

191 views
Skip to first unread message

The Pianoman

unread,
Feb 26, 2016, 12:00:35 PM2/26/16
to wcm-io Developers
Hi,

I would like to access the io.wcm.config.api.Configuration inside a servlet.

Just like that:

import io.wcm.config.api.Configuration;

@SlingServlet(paths = "/bin/servlet", methods = "GET")
public class MyServlet extends SlingSafeMethodsServlet {
@Reference
private Configuration cfg;

protected void doGet(...) { cfg.get(...) }
}

When I add the @Reference, the servlet will not be deployed.
Looking into the Web Console of AEM, there is the message:
xxx.MyServlet State unsatisfied (Reference)

What am I doing wrong?
How can I access the Configuration from within a servlet?

Thanks,
Bernhard

Stefan Seifert

unread,
Feb 27, 2016, 3:02:34 AM2/27/16
to wcm-i...@googlegroups.com
hello bernhard.

you are mixing up OSGi dependencies and the adaptTo() concept here.

there is no OSGi service registered to "io.wcm.config.api.Configuration" available, so the OSGi @Reference cannot be satisfied.

inside a Sling Model you could inject a Configuration with @Self annotation when the model itself is adapted from a SlingHttpServletRequest or Resource.

but in this case you are inside an OSGi component (registered by @SlingServlet). you can get the configuration by either doing

request.adaptTo(Configuration.class)

or

resource.adaptTo(Configuration.class)

in the case the configuration resource you are interested in belongs to a resource that is not the resource associated with the request.

see [1] for usage samples.

stefan

[1] http://wcm.io/config/api/usage-api.html
>--
>You received this message because you are subscribed to the Google Groups
>"wcm-io Developers" group.
>To unsubscribe from this group and stop receiving emails from it, send an
>email to wcm-io-dev+...@googlegroups.com.
>To view this discussion on the web visit
>https://groups.google.com/d/msgid/wcm-io-dev/9ac280dd-e6f1-4e5b-817a-
>f374381d3a8a%40googlegroups.com.
>For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages