2013-06-18 62 views
0

我有公開以下服務束的:如何從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實現。

乾杯, 鮑里斯

回答

2

我想你已經錯過了聲明式服務(DS):-) DS的整個想法幾位您在XML中指定的依賴(或者很多很多與更好註釋)。這是servlet應該什麼樣子:

@Component(provide=Servlet.class) 
public class MyServlet extends HttpServlet { 
    T myService; 

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { 
    myService.invokeMyServiceMethod(); 
    } 

    @Reference 
    T setT(T t) { 
    myService =t; 
    } 
} 

唯一需要的是確保你已經安裝了Apache菲利克斯的HTTP白板束(是的,它工作正常春分,標準的美女)。該捆綁包監視正在註冊的所有Servlet服務並將它們添加到Http服務。由於DS確保您的組件在擁有myService之前未被註冊,因此myService肯定是非空的。這被稱爲DS靜態模式:在你被調用之前,你的所有依賴關係都會被滿足。

如果你很勇敢,你可以聲明setT方法是動態的。那麼即使沒有T服務,你的組件也會被註冊。例如。允許你告訴主叫方沒有服務。這被稱爲動態模式。

使用的註釋是標準DS。它們由bnd處理並轉換爲XML。這適用於maven,gradle等,但最重要的當然是bndtools。