Reputation: 167
In AEM, I need to configure a list of strings and share it across multiple services. What is the best way to accomplish this? The list needs to be configurable at run time.
Upvotes: 3
Views: 1587
Reputation: 21500
You could create a dedicated configuration service that you configure and that is referenced by all other OSGi services that require one or more of the configured values.
Example configuration service
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;
}
}
This is the bare minimum of such a class. But it will create a configurable OSGi service that you can configure in Apache Felix Configuration Manager (/system/console/configMgr
).
Note: It is important to use metatype = true
in the @Component
annotation.
The next step is to reference this service in the "consuming" services.
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();
}
}
Note: This example uses the Apache SCR annotations which can be used with AEM out of the box. You can learn more about SCR annotations used in this example (@Service
, @Component
, @Property
, @Reference
) in the official documentation: Apache Felix SCR Annotation Documentation
Upvotes: 6