2013-07-25 143 views
1

我是一個建造一個OSGI框架,我想知道是否有辦法讓所有綁定到我的bundle?有沒有辦法找出哪些軟件包使用我的軟件包?

這是因爲我爲這些軟件包提供服務,並提供新資源來優化我的優勢,同時提供此服務。我還提供了一種在不再需要時摧毀這些資源的方法,但是我希望在沒有首先刪除其使用的資源的情況下捆綁銷燬時解除安全保護。

我可以使用我的BundleContext嗎?

回答

3

你似乎在問兩個不同的問題。在第一段中,你問的是綁定到你的綁定,我解釋這意味着綁定導入你的導出包。第二,你問的是你的服務消費者;這些是正交的問題。

對於第一個問題,你可以使用BundleWiring API:

BundleWiring myWiring = myBundle.adapt(BundleWiring.class); 
List<BundleWire> exports = myWiring.getProvidedWires(PackageNamespace.PACKAGE_NAMESPACE); 
for (BundleWire export : exports) { 
    Bundle importer = export.getRequirerWiring().getBundle() 
} 

對於服務,您可以使用ServiceFactory模式。通過將您的服務註冊爲ServiceFactory的實例,而不是直接作爲服務接口的實例,您可以跟蹤使用服務的包。下面是使用這種模式的服務實現的骨架:

public class MyServiceFactory implements ServiceFactory<MyServiceImpl> { 

    public MyServiceImpl getService(Bundle bundle, ServiceRegistration reg) { 
     // create an instance of the service, customised for the consumer bundle 
     return new MyServiceImpl(bundle); 
    } 

    public void ungetService(Bundle bundle, ServiceRegistration reg, MyServiceImpl svc) { 
     // release the resources used by the service impl 
     svc.releaseResources(); 
    } 
} 

UPDATE:既然要實現您的DS使用的服務,事情有點容易。 DS管理實例爲你的創作...唯一稍微棘手的事情是找出哪些包是你的消費者:

@Component(servicefactory = true) 
public class MyComponent { 

    @Activate 
    public void activate(ComponentContext context) { 
     Bundle consumer = context.getUsingBundle(); 
     // ... 
    } 
} 

在很多情況下,你甚至都不需要得到ComponentContext和消費束。如果您爲每個使用者包分配資源,那麼您可以將這些資源保存到組件的實例字段中,並記住在停用方法中清理它們。 DS會爲每個消費者套件創建一個組件類的實例。

+0

我正在使用聲明式服務,所以我不確定如何實現這一點,看到一個servicefactory,我只是將它的屬性設置爲「true」。 當我使用context.getService(ServiceReference sv)時,將自動調用我的servicefactory的get方法嗎? – Don

+0

啊,DS使它更容易。我會更新我的答案。 –

相關問題