我有公開以下服務束的:如何從OSGi的HTTP服務消耗OSGi服務
在OSGI-INF/config.xml中
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
name="com.example.MyService" modified="updated" immediate="true">
<implementation class="com.example.impl.MyServiceImpl"/>
<service>
<provide interface="com.example.MyService"/>
</service>
</scr:component>
下一步,我想消費這從束B.一個servlet服務
我做的是以下幾點:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
BundleContext bundleContext = (BundleContext) getServletContext().getAttribute("osgi-bundlecontext");
if (bundleContext != null) {
// Here MyService is the service exposed as declarative service
MyService myService = getService(bundleContext, MyService.class);
if(myService != null) {
// I want to invoke some method declared in MyService interface
myService.invokeMyServiceMethod();
}
}
}// end of doPost
protected <T> T getService(BundleContext bundleContext, Class<T> type) {
ServiceReference<T> serviceRef = bundleContext.getServiceReference(type);
if (serviceRef == null) {
return null;
}
T service = bundleContext.getService(serviceRef);
return service;
}// end of getService method
由於我的服務n OSGi來來往往,假設即使doPost方法中非空引用的檢查通過,下一條語句myService.invokeMyServiceMethod()也不會拋出NPE嗎?
如何保證我將始終從服務註冊表中獲取對MyService的有效引用?
如果這不是從Http Service獲取服務引用的正確方法,那麼正確的方法是什麼?
我使用Equinox作爲OSGi實現。
乾杯, 鮑里斯