如何注销OSGi服务 [英] how to unregister an OSGi service
问题描述
我有以下测试代码,该代码应注册而不是注销测试服务.我在Eclipse 4.5.2 Mail-Demo应用程序中对其进行了测试.问题在于该服务并非未注册,对该服务的第二次调用也不为空.
I have the following test code, which should register and than unregister a test service. I tested it in an Eclipse 4.5.2 Mail-Demo appliation. The problem is that the service is not unregisted, the second call for the service is not null.
BundleContext bundleContext = Activator.getDefault().getBundle().getBundleContext();
ServiceRegistration<ITestService> registration = bundleContext.registerService(ITestService.class, new TestService(), null);
ServiceReference<ITestService> serviceReference = bundleContext.getServiceReference(ITestService.class);
bundleContext.ungetService(serviceReference);
serviceReference = bundleContext.getServiceReference(ITestService.class);
System.out.println("should be null but is not: " + serviceReference);
这是我得到的输出:
should be null but is not: {unregister.osgiservice.ITestService}={service.id=172, service.bundleid=8, service.scope=singleton}
如何正确注销服务?
确定,如果我在服务下方添加了代码,则找到 ServiceRegistration.unregister()
.这就引出了下一个问题,如何从另一个注册服务的地方获取 ServiceRegistration
?
How do I unregister the service correctly?
Ok I found ServiceRegistration.unregister()
, if I add the code below the service is unregisted. Which brings up the next question, how do I get the ServiceRegistration
from another place where the service is registered?
registration.unregister();
serviceReference = bundleContext.getServiceReference(ITestService.class);
System.out.println("now the service is null: " + serviceReference);
输出:
should be null but is not: {unregister.osgiservice.ITestService}= service.id=174, service.bundleid=8, service.scope=singleton}
now the service is null: null
推荐答案
尽管上面有greg的回答,但我发现使用内部类的这种讨厌的解决方法:
Despite the answer of greg above, I found this nasty workaround using internal classes:
((org.eclipse.osgi.internal.serviceregistry.ServiceReferenceImpl) serviceReference).getRegistration().unregister();
当然这很不好,但是我需要一种解决方法来获取 ServiceRegistration
.我无法在启动时存储 ServiceRegistration
,因为我正在使用 Eclipse Gemini蓝图(以前的Spring DM)注册我的服务.
Sure this is bad, but I need a solution to get the ServiceRegistration
. I can't store the ServiceRegistration
on startup since I'm using Eclipse Gemini Blueprint (former Spring DM) to register my services.
这篇关于如何注销OSGi服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!