Search code examples
javaosgibundle

OSGI: Activate and Bind methods changes starting order after restarting the bundle


in my project I have an OSGI bundle. In this bundle I have an Activated method and a bind(to ConfigurationAdmin) method.

When I run the project for the first time the Activated method is called first, so i can initialize all the things I need, but if I stop the bundle and then start it again the bind method is called first and I have a nullpointer(because the initializations in Activate are not called yet).

The reference at the bind method is "cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC"

Why when started for the second time the order changes?

@Component(configurationPid = "ConsulService", immediate = true, service = ConsulService.class)
public class ConsulServiceImpl implements ConsulService {

private ConfigurationAdmin configurationAdmin;
private BundleContext context;
private Consul consul;

@Override
public AgentClient agentClient() {
    return consul.agentClient();
}

@Override
public KeyValueClient keyValueAgent() {
    return consul.keyValueClient();
}

@Activate
public void activate(BundleContext bundleContext) {
//this cause the nullpointer after the stop and the restarting of this bundle
//since this method is not called "consul" is null
    this.consul = Consul.builder().build();
    this.context = bundleContext;
}

...

@Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, unbind = "unbindConfigurationAdmin")
public void bindConfigurationAdmin(final ConfigurationAdmin configurationAdmin) {
    this.configurationAdmin = configurationAdmin;
    // Here I have nullpointer because consul is not initializated 
    KeyValueClient keyValueAgent = keyValueAgent();
    ...
}

Solution

  • It seems that the binding method is called when the service is available. At the first start when the Activated method is called the configurationAdmin is not available yet, but when I stop the bundle and then restart it again the configurationAdmin is available and the bind is called before activated.