Reputation: 1083
I need to get some OSGI configuration values via plain Java class which is not registered as service so I cannot use @Reference or @Inject annotation. I have used Bundle context to get the config but it is working.
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 class
@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;
}
is it correct way of doing? if not what is correct option to get it?
Upvotes: 1
Views: 2268
Reputation: 19606
You can get any configuration using ConfigurationAdmin. For your DS components the pid by default is the FQName of your component class.
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);
Upvotes: 2