如何在 AEM 中跨多个 OSGI 服务共享配置

How to share a configuration across multiple OSGI services in AEM

在 AEM 中,我需要配置一个字符串列表并在多个服务之间共享它。完成此任务的最佳方法是什么?该列表需要在 运行 时配置。

您可以创建一个您配置的专用配置服务,该服务由需要一个或多个配置值的所有其他 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;
    }
}

这是此类 class 的最低限度。但它会创建一个可配置的 OSGi 服务,您可以在 Apache Felix 配置管理器中配置该服务 (/system/console/configMgr)。

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

下一步是在 "consuming" 服务中引用此服务。

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();
    }
}

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