使用OSGi包的配置

问题描述 投票:0回答:3

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

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

java osgi apache-karaf karaf
3个回答
0
投票

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

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


0
投票

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

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


0
投票

原因是updated()ManagedService方法的竞争条件。它在调用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
}

这会产生以下输出:

[WARN ] [..Activator] - properties.get() on updated():hello
[DEBUG] [..Activator] - context.getProperty():null
[DEBUG] [..Activator] - System.getProperty():null
[DEBUG] [..Activator] - configRef.properties.get():null
[DEBUG] [..Activator] - d.get():null
[DEBUG] [..Activator] - configuration.get():hello

更改updated()方法以填充类级字典字段似乎可行。在实践中,在configuration方法中使用d用于start()可能是一个更好的主意,但是这段代码显示了真正发生的事情。

感谢大家的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.