【问题标题】:How to read OSGI configuration via plain Java class如何通过纯 Java 类读取 OSGI 配置
【发布时间】:2018-05-18 16:20:36
【问题描述】:

我需要通过未注册为服务的普通 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;
    }

这是正确的做法吗?如果不是什么是正确的选择?

【问题讨论】:

  • 我不明白你想达到什么目的。您想从配置管理员获取配置还是从服务获取服务属性?
  • 我想在纯 java 中获得一个 cofig 值

标签: java osgi aem


【解决方案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);

【讨论】:

  • 您好,Christaian,感谢您的回复。我在第 3 行看到编译时错误,BundleContext 类型中的方法 getServiceReference(String) 不适用于参数 (Class)。实际上我导入了“org.osgi.framework.ServiceReference;”
  • 您可能使用的是旧版本的 OSGi API。在这种情况下尝试使用 ConfigurationAdmin.class.getName()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-19
  • 2015-01-15
  • 2015-12-10
  • 2015-08-25
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多