如何在AEM中的多个OSGI服务之间共享配置

问题描述:

在AEM中,我需要配置字符串列表并在多个服务之间共享。什么是完成这个最好的方法?该列表需要在运行时配置。如何在AEM中的多个OSGI服务之间共享配置

+0

你见过吗? http://www.nateyolles.com/blog/2015/10/updating-osgi-configurations-in-aem-and-sling。 OSGI服务读取写入OSGI配置。 –

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

+0

非常整齐的解释。但是,我们不应该在这里使用接口?并在类中实现,并将接口声明为服务。这似乎足够安全。 – theanubhava

+0

@theanubhava正如我在文中提到的:这是最低限度的。很明显,你可以在这里改进很多东西。为了简洁起见,我选择了尽可能最短的例子来说明基本原理。通常情况下,你可以使用接口并将它们分割成一个'api'和'impl'包等。 – Jens