开发者

Osgi getService()

In our project (Osgi, Spring-Dm, Apache-Felix) we are having some issue on production when BundleContext.getServic开发者_C百科e() return null. It happens very seldom, and not at the start, so it's not a misconfiguration problem.

An alternative could be using ServiceTracker to locate the service, but because the error is quite rare I'm not sure if changing it would solve the situation.


The OSGi-specification says that the method returns

  • A service object for the service associated with reference
  • or null if
    • the service is not registered
    • the service object returned by a ServiceFactory does not implement the classes under which it was registered
    • the ServiceFactory threw an exception

My first guess would be that the service is not registered.

By the way, using Spring-DM should make most programmatic accesses to the service registry unneccessary. At least in our companies these calls have been generally forbidden and are only allowed in lower level technical code.


Uberto, it's not at all weird for the service not to be registered yet. OSGi is dynamic. Services come and go. If you attempt to access a service before it has been registered then you will get null.

When you do a plain getService() you are kind of assuming that the service already exists. If you need the service to be there, you should instead do something that involves waiting for the registration event. This can be done with ServiceTracker, but it is rather low level. As others have pointed out, using something like Spring-DM or Declarative Services makes this quite easy and robust.


I can confirm that race conditions can occur if you use the ServiceTracker! Sometimes, the ServiceTracker can not catch a Service even though the service is registered. To solve the problem I use waitForService() instead of getService().

Regards Roland


If the ServiceReference is not null and getting null pointer while getService(serviceReference) then the service implementation class is not properly initialized.

Make sure the constructor of the service implementation class is public and no errors in object creation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜