【发布时间】:2011-12-08 12:02:42
【问题描述】:
以我对 OSGi 的熟练程度,我可以从以下位置获取属性字符串:
- BundleContext.getProperty(key)(存储在“conf/config.properties”中)
-
ComponentContext.getProperties().get(key)(存储在 bundle 的 'MANIFEST.MF' 中)
服务组件:\ foo.bar.impl.FixServer;application="quickfix.Application";properties:="acceptor.resourcename=acceptor.cfg"
我想获取捆绑清单中的属性,可在捆绑级别(即 BundleContext)访问,它高于“服务组件”(即 ComponentContext)。
谁能告诉我如何做到这一点?
附录
来自 AValchev 和 Neil Bartlett 的回答,
java.util.Dictionary headers = Bundle.getHeaders();
是一个很好的方法。
于 2011 年 12 月 10 日编辑
但是,JAR Manifest 语法(要求键中的第一个字符为大写,并且不允许使用 '.' 字符)会破坏我的应用程序键常量,除非我进行一些重构。
如果我这样做了,如果我以后使用 .properties 文件,应用程序将再次崩溃。
为了克服 JAR 清单语法的(IMO)“限制”,我提出了这个单一的清单条目:
Bundle-Properties: \
foo.bar.prefix=MS,\
foo.bar.hostname=127.0.0.1,\
foo.bar.port=8106,\
foo.bar.homepath=/foo/bar/E3,\
foo.bar.secure=false,\
,以及将字符串消化成属性的代码:
java.util.Properties properties = new java.util.Properties();
java.util.Dictionary headers = bcontext.getBundle().getHeaders();
String manifest_key = "Bundle-Properties";
String manifest_value = (String) headers.get(manifest_key);
if (manifest_value != null) {
String[] t = manifest_value.split(",");
for (int i = 0; i < t.length; i++) {
String[] u = t[i].split("=");
if (1 < u.length) {
String key = u[0];
String value = u[1];
properties.setProperty(key, value);
}
}
}
【问题讨论】: