Kamil
Kamil

Reputation: 1538

How to config bundle to start after referenced bundle starts?

Service is defined in first bundle in xml.

In the second bundle a reference is defined in xml using the same interface.

In the second bundle in the activator I get the service reference by:

ServiceReference servReference = context.getServiceReference(MyInterface.class.getName());

and everything works nice unless the first bundle is started after the second.

Then I get:

org.osgi.framework.BundleException: Activator start error in bundle foo.bar.baz [123].
Caused by: java.lang.NullPointerException: Specified service reference cannot be null.`

After a while the first bundle starts and everything works fine.

So my question is how to force second bundle to wait for the first one to start?

Upvotes: 0

Views: 666

Answers (1)

Christian Schneider
Christian Schneider

Reputation: 19626

In OSGi you should never wait for another bundle or to start or service to come up. Especially never wait in an Activator as it will block the startup of other bundles.

In your case you need to react on the event that the MyInterface service comes up.

If you need to use plain OSGi API then you use a ServiceTracker for this. You override the addingService and removedService methods and in there control the lifecycle of the class that needs the service. So when the service comes up you create the instance of the class, inject the service and eventually fire up some callback to let the class know the service is there. When the service goes away you tell the instance to shutdown. As an example see "Tracking a service".

As you can imagine this is simple for tracking a single service and injecting it in a class instance but it becomes really difficult once more services and instances are involved. This is why you should normally not use the plain OSGi APIs.

So you should use a dependency management framework like declarative services or blueprint that takes care of this heavy lifting for you.

Upvotes: 2

Related Questions