【问题标题】:How to share a configuration across multiple OSGI services in AEM如何在 AEM 中跨多个 OSGI 服务共享配置
【发布时间】:2017-04-18 22:27:48
【问题描述】:

在 AEM 中,我需要配置一个字符串列表并在多个服务之间共享它。实现这一目标的最佳方法是什么?该列表需要在运行时进行配置。

【问题讨论】:

标签: osgi aem


【解决方案1】:

您可以创建一个您配置的专用配置服务,并被所有其他需要一个或多个配置值的 OSGi 服务引用。

示例配置服务

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.ComponentContext;

@Service(ConfigurationService.class)
@Component(immediate = true, metatype = true)
public class ConfigurationService {

    @Property
    private static final String CONF_VALUE1 = "configuration.value1";
    private String value1;

    @Property
    private static final String CONF_VALUE2 = "configuration.value2";
    private String value2;

    @Activate
    public void activate(final ComponentContext componentContext) {
        this.value1 = PropertiesUtil.toString(componentContext.get(CONF_VALUE1), "");
        this.value2 = PropertiesUtil.toString(componentContext.get(CONF_VALUE2), "");
    }

    public String getValue1() {
        return this.value1;
    }

    public String getValue2() {
        return this.value2;
    }
}

这是此类课程的最低要求。但它会创建一个可配置的 OSGi 服务,您可以在 Apache Felix 配置管理器 (/system/console/configMgr) 中进行配置。

注意:在@Component 注解中使用metatype = true 很重要。

下一步是在“消费”服务中引用此服务。

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.component.ComponentContext;

@Service(MyService.class)
@Component(immediate = true, metatype = true)
public class MyService {

    @Reference
    private ConfigurationService configurationService;

    @Activate
    public void activate(final ComponentContext componentContext) {
        this.configurationService.getValue1();
    }
}

注意:此示例使用可与 AEM 一起使用的 Apache SCR 注释。您可以在官方文档中了解有关此示例中使用的 SCR 注释(@Service@Component@Property@Reference)的更多信息:Apache Felix SCR Annotation Documentation

【讨论】:

  • 非常简洁的解释。但是,我们不应该在这里使用接口吗?以及在类中实现,并将接口声明为服务。这似乎足够安全。
  • @theanubhava 正如我在文本中指出的那样:这是最低要求。显然,这里有很多可以改进的地方。为简洁起见,我选择了尽可能短的示例来演示基本原理。通常,您会使用接口并将它们拆分为 apiimpl 捆绑包等。
  • blog.vogella.com/2016/09/26/… 中讨论了对这个主题可能有用的另一件事,即添加 configurationPid=com.package。消费服务的@Component 中的 ConfigurationService。
猜你喜欢
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-13
  • 2018-03-16
相关资源
最近更新 更多