我需要通过普通的Java类获取一些OSGI配置值,它没有注册为服务,所以我不能使用@Reference或@Inject注释。我使用了Bundle上下文来获取配置,但它正在运行。
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;
}
这是正确的做法吗?如果没有什么是正确的选择吗?
答案 0 :(得分:1)
您可以使用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);