【问题标题】:OSGI: Activate and Bind methods changes starting order after restarting the bundleOSGI:Activate 和 Bind 方法在重新启动捆绑包后更改启动顺序
【发布时间】:2020-07-20 15:26:32
【问题描述】:

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

当我第一次运行项目时,首先调用 Activated 方法,因此我可以初始化我需要的所有东西,但是如果我停止捆绑然后再次启动它,首先调用绑定方法并且我有一个nullpointer(因为尚未调用 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();
    ...
}

【问题讨论】:

  • 你停止了什么捆绑?包含您的组件的捆绑包还是托管您绑定到的服务的捆绑包?
  • 嗨,Christian,我停止使用我的组件进行捆绑。 ConfigurationAdmin 是 OSGI 的一项服务
  • 那听起来很奇怪..你能显示组件的相关代码吗?
  • 我已经用代码编辑了我的问题

标签: java osgi bundle


【解决方案1】:

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

【讨论】:

  • 我用的是DS 1.3,好像不支持
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多