OSGI:激活和绑定方法在重新启动捆绑包后更改启动顺序

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

在我的项目中,我有一个 OSGI 包。在这个包中,我有一个 Activated 方法和一个 bind(to ConfigurationAdmin) 方法。

当我 运行 项目第一次调用 Activated 方法时,我可以初始化我需要的所有东西,但是如果我停止 bundle 然后再次启动它,绑定方法是首先调用,我有一个空指针(因为尚未调用 Activate 中的初始化)。

绑定方法的引用是"cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC"

为什么第二次启动时顺序变了?

@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();
    ...
}

绑定方法可以在激活方法之前调用。事实上,绑定方法必须在静态引用的激活方法之前被调用。将 activate 方法视为 post-construct 方法。如果您需要将激活方法作为构造函数,请使用 DS 1.4 支持的构造函数注入。

好像是服务可用时才调用绑定方法。 第一次启动时调用 Activated 方法时 configurationAdmin 尚不可用,但是当我停止捆绑然后再次重新启动它时,configurationAdmin 可用并且在激活之前调用绑定。