在 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;
}
}
这是此类的最低要求。但它会创建一个可配置的 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();
}
}
注意:此示例使用 Apache SCR 注释,它可以与开箱即用的 AEM 一起使用。您可以了解有关此示例中使用的 SCR 注释的更多信息(@Service
、@Component
、@Property
、@Reference
) 在官方文档中:Apache Felix SCR Annotation Documentation
关于osgi - 如何在 AEM 中跨多个 OSGI 服务共享配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43483237/