Getting OSGi services from a bundle in Sling/CQ

寵の児 提交于 2019-12-12 07:32:49

问题


I am using Day CQ. I want to store some data in a SQL Server DB, using the connection pool available in the Felix console. I can do this from a JSP, by using the "sling" object of type SlingScriptHelper defined in the defineObjects tag

sling.getService(DataSourcePool.class).

However, I want to use a servlet created in an OSGi bundle to handle requests from the client. The servlet doesn't have a defineObjects tag, so the "sling" object is not defined. I don't see a way to create a valid SlingScriptHelper object in my servlet, but it seems like it has to be possible.

Is there a way?


回答1:


To get a service from a java OSGi component you don't need the SlingScriptHelper, you can either use the BundleContext.getService(...) method, or use SCR annotations to let SCR inject the service in your component.

As an example, you can look at how some components in Sling's Slingbucks sample use SCR annotations, the ConfirmedOrdersObserver class for example gets the SlingRepository in this way:

   @Reference
   private SlingRepository repository;

See http://felix.apache.org/site/apache-felix-maven-scr-plugin.html for the Maven plugin that handles these annotations.




回答2:


You can use the BundleContext to get to the Service, by using the #getServiceReference and #getService methods. For example, if you were interested in the ResourceResolverFactory, you could get it like so:

BundleContext bundleContext = FrameworkUtil.getBundle(MyClass.class).getBundleContext();
ServiceReference factoryRef =
     bundleContext.getServiceReference(ResourceResolverFactory.class.getName());
ResourceResolverFactory resolverFactory = 
    (ResourceResolverFactory) bundleContext.getService(factoryRef);



回答3:


YourClass obj = this.getSlingScriptHelper().getService(yourclass.class);
obj.whatever();


来源:https://stackoverflow.com/questions/8595279/getting-osgi-services-from-a-bundle-in-sling-cq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!