我需要通过纯Java类获取一些OSGI配置值,该类未注册为服务,因此我无法使用@Reference或@Inject注释。我已经使用 Bundle context 来获取配置,但它正在工作。
public void getArticleName() {
final BundleContext bundleContext = FrameworkUtil.getBundle(ArticleNameService.class).getBundleContext();
try {
String articleName = (String) bundleContext.getService((bundleContext.getServiceReferences(ArticleNameService.class.getName(), " article.name "))[0]);
LOG.info("articleName......"+ articleName);
} catch (InvalidSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
服务等级
@Service(ArticleNameService.class)
@Component(
metatype = true)
@Properties({
@Property(
name = "article.name", unbounded = PropertyUnbounded.ARRAY, cardinality = Integer.MAX_VALUE,
label = "article addrnameess"),
})
public class ArticleNameServiceImpl implements ArticleNameService
{
private static final String ARTICLE_NAME = "article.name";
private String[] articleName;
protected final void activate(final ComponentContext componentContext)
{
final Dictionary<String, Object> configurationProperties = componentContext.getProperties();
if (configurationProperties != null)
{
articleName = PropertiesUtil.toStringArray(configurationProperties.get(ARTICLE_NAME));
}
}
@Override
public final String[] getArticeName()
{
return articleName;
}
这是正确的做法吗?如果不是,获得它的正确选项是什么?
最佳答案
您可以使用 ConfigurationAdmin 获取任何配置。对于 DS 组件,默认情况下 pid 是组件类的 FQName。
Bundle bundle = FrameworkUtil.getBundle(this.getClass());
BundleContext context = bundle.getBundleContext();
ServiceReference<ConfigurationAdmin> reference = context.getServiceReference(ConfigurationAdmin.class);
ConfigurationAdmin configAdmin = context.getService(reference);
Configuration conf = configAdmin.getConfiguration("yourpid");
String articleName = (String)conf.getProperties().get("article.name");
context.ungetService(reference);
关于java - 如何通过普通 Java 类读取 OSGI 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415557/