次のサービスを公開するバンドル A があります。
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 のサーブレットからこのサービスを利用したいと考えています。
私がすることは次のとおりです。
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
OSGi のサービスは行き来するので、doPost メソッドの非 null 参照のチェックに合格しても、次のステートメントmyService.invokeMyServiceMethod()は NPE をスローしないと想定するのは正しいですか?
サービス レジストリから MyService への有効な参照を常に取得することを保証するにはどうすればよいですか?
これが Http Service からサービス参照を取得する正しい方法でない場合、正しい方法はどれですか?
OSGi の実装として Equinox を使用しています。
乾杯、ボリス