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);
This is the output I get:
should be null but is not: {unregister.osgiservice.ITestService}={service.id=172, service.bundleid=8, service.scope=singleton}
How do I unregister the service correctly?
EDIT:
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);
Output:
should be null but is not: {unregister.osgiservice.ITestService}= service.id=174, service.bundleid=8, service.scope=singleton}
now the service is null: null
ungetService
just drops the particular service reference, it does not unregister the service.
registerService
returns a ServiceRegistration
which you can use to unregister the service:
ServiceRegistration<ITestService> reg = bundleContext.registerService(ITestService.class, new TestService(), null);
...
reg.unregister();
It is up to you to track the service registrations. Many plugins store them in the plugin Activator. It is also common to register the service in the Activator start
method and unregister in the stop
method.
Despite the answer of greg above, I found this nasty workaround using internal classes:
((org.eclipse.osgi.internal.serviceregistry.ServiceReferenceImpl) serviceReference).getRegistration().unregister();
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.