我正在制作一个OSGi包,并且有一些所需的可配置参数。我关注了instructions for karaf,配置值显示在webconsole中。但它们如何在Java中使用?
我在执行器,context.getProperty("prop1")
甚至System.getProperty("prop1")
中尝试过registering a ManagedService。该属性始终返回null。这应该很容易。我错过了什么?
它显示了如何以编程方式和使用蓝图处理ConfigAdmin属性。
原因是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()
可能是一个更好的主意,但是这段代码显示了真正发生的事情。
感谢大家的帮助!