java - 如何通过普通 Java 类读取 OSGI 配置

标签 java osgi aem

我需要通过纯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/

相关文章:

java - 调用方法 osgi aem read 子服务时发生 com.sun.jdi.InitationException

java - OSGi `uses` 约束违规,即使存在兼容的导出器

aem - javax.jcr.nodetype.ConstraintViolationException : No matching property definition: PROPERTY

java - 没有实现时如何获取 slf4j 控制台输出?

java - Eclipse RCP 中的 JInternalFrame 替代方案

osgi - 将 osgi 包部署到 cics

jackrabbit - 是否可以通过 GUID 访问节点?

javascript - Vue.js 在 DOM 树突变后挂载组件以添加 vue 组件

java - 比较 2 个不同对象列表的多个字段

java - 在 Jython(和 Gephi)中查找