Is it valid to deactivate a component in OSGi manually if I am using Declarative Services?
For example, let's say I have a component, with the implementation:
//component
class Overseer(){
List<ServiceReference> serviceRefs = ...//populate
private void doStuff(){
serviceRef = serviceRefs[i];
if(dontNeedThisAnymore){
serviceRefs.remove(serviceRef);
serviceRef.getBundle().stop();
}
}
The best way to do this is from another component in the same bundle, using the ComponentContext
API.
You can write a component so that it takes ComponentContext
as a param to its activate method. That interface has enableComponent
and disableComponent
methods that can be used to enable/disable other components in the same bundle.
I call this a "gatekeeper" component because it can be used to setup resources needed by the other components before enabling them. For example, you may have multiple components that need a database to be started up before they can do their job... the gatekeeper would take care of starting the database and then call enableComponent(null)
to enable the other components. Similarly if the gatekeeper could detect that the database has shutdown and at that point disable the other components. In order for this to work, all components in the bundle except for the gatekeeper need to be set initially to enabled="false"
.