天天看點

《深入了解OSGi:Equinox原理、應用與最佳實踐》一3.6 Bundle上下文

osgi容器中運作的各個bundle共同構成了一個微型的生态系統,bundle的許多行為都無法孤立進行,必須在特定的上下文環境中才有意義,因為要與上下文的其他bundle或osgi架構進行互動。在代碼中使用bundlecontext對象來代表上下文環境,當bundle啟動的時候,osgi架構就建立這個bundle的bundlecontext對象,直到bundle停止運作從osgi容器解除安裝為止。bundle在進行以下操作時,需要通過bundlecontext對象來完成。

安裝一個新的bundle到目前osgi容器之中(bundlecontext.installbundle()方法)。

從目前osgi容器中擷取已有的bundle(bundlecontext.getbundle()方法)。

在osgi容器中注冊服務(bundlecontext.registerservice()方法)。

從目前osgi容器中擷取已有的服務(bundlecontext.getservice()方法)。

在osgi容器中注冊事件監聽器(bundlecontext.addbundlelistener()、bundle- context.addframeworklistener()方法)。

從bundle的持久儲存區中擷取檔案(bundlecontext.getdatafile()方法)。

擷取bundle所處環境的環境屬性(bundlecontext.getproperty()方法)。

每個bundle的bundlecontext對象都是在調用bundle.start()方法時由osgi架構建立并以方法參數的形式傳入到bundle中,實作bundle時一般會把這個對象的引用保留起來,以便在bundle其他代碼中使用,示例如下:

上下文對象涉及bundle的資料安全和資源配置設定,它應當是bundle私有的,不應當傳遞給其他bundle使用。在bundle的stop()方法執行完之後,bundle對象就會随之失效,如果在bundle停止後繼續使用bundlecontext對象,那麼osgi架構就會抛出illegalstateexception異常。

繼續閱讀