【问题标题】:Using configuration for an OSGi bundle使用 OSGi 包的配置
【发布时间】:2019-02-09 00:33:41
【问题描述】:

我正在制作一个 OSGi 包,并有一些它需要的可配置参数。我关注了instructions for karaf,配置值显示在 webconsole 中。但是如何在 Java 中使用它们呢?

我在执行器中尝试了context.getProperty("prop1")System.getProperty("prop1"),甚至registering a ManagedService。该属性始终返回为空。这应该很容易。我错过了什么?

【问题讨论】:

  • 对于 ManagedService:您是否检查了服务 PID(也显示在 webconsole 中)是否与配置 PID 匹配?

标签: java osgi apache-karaf karaf


【解决方案1】:

将配置属性放到etc/system.propertiesSystem.getProperty() 应该可以工作。

使用属性占位符(请参阅40482233)和ConfigurationAdmin(请参阅30474886)也可以实现同样的效果。

【讨论】:

    【解决方案2】:

    看看这个教程:http://liquid-reality.de/display/liquid/2011/09/23/Karaf+Tutorial+Part+2+-+Using+the+Configuration+Admin+Service

    它展示了如何以编程方式和使用蓝图来处理 ConfigAdmin 属性。

    【讨论】:

      【解决方案3】:

      原因是ManagedServiceupdated() 方法的竞争条件。它在调用registerService() 时执行,但configRef 不返回具有配置信息的properties。此外,传递给 registerService() 的字典不会填充现有配置值。

      这里有一些示例 groovy 代码可以更好地解释。 (注意:properties 是 groovy 中的保留字。也许这会导致一些问题):

      class Activator implements BundleActivator, ManagedService{
      private ServiceRegistration<ManagedService> configRef
      private Dictionary<String,?> configuration
      
      @Override
      void start(BundleContext context) throws Exception {
          Dictionary d=new Hashtable()
          d.put(Constants.SERVICE_PID,myPID)
          configRef=context.registerService(ManagedService,this,d)
      
          log.debug("context.getProperty():"+context.getProperty("prop1"))
          log.debug("System.getProperty():"+System.getProperty("prop1"))
          log.debug("configRef.properties.get():"+configRef.properties.get("prop1"))
          log.debug("d.get():"+d.get("prop1"))
          log.debug("configuration.get():"+configuration.get("prop1"))
       }
      
      ...
      
      @Override
      void updated(Dictionary<String, ?> properties) throws ConfigurationException {
          log.warn("properties.get() on updated():"+properties.get("prop1"))
          configuration=properties
      }
      

      这会产生以下输出:

      [警告] [..Activator] - 更新()上的属性.get():你好 [调试] [..Activator] - context.getProperty():null [调试] [..Activator] - System.getProperty():null [调试] [..Activator] - configRef.properties.get():null [调试] [..Activator] - d.get():null [调试] [..Activator] - configuration.get():hello

      更改updated() 方法以填充类级别的字典字段似乎有效。实际上,在start() 方法中使用configuration 代替d 可能是一个更好的主意,但这段代码显示了实际发生的情况。

      感谢大家的帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 2010-12-02
        • 1970-01-01
        相关资源
        最近更新 更多