Receiving configuration data by using the ManagedService interface

Liberty configuration is managed by the OSGi Configuration Admin service and can be accessed according to the OSGi Configuration Admin service specification. Sets of configuration properties are identified by a persisted identity (PID) that is used to associate an element in the server.xml file, where the PID is used as the element name, with a component that registers to receive the properties.

About this task

For an OSGi bundle whose lifecycle is managed by using the BundleActivator interface, a straightforward way to receive the configuration properties is to implement the org.osgi.service.cm.ManagedService interface, which specifies the PID as one its properties.

Example

Remember:
  1. In Eclipse, you must select an SPI target runtime from Window > Preferences > Plug-In Development > Target Platform.

  2. Add the following statement to your MANIFEST.MF file:
    Import-Package: org.osgi.service.cm;version="1.5.0"
  3. Press Ctrl + Shift + O to update your bundle activator.

In this example, the Activator class implements the ManagedService interface in addition to the BundleActivator interface, and receives configuration properties by using the updated method. You can provide default property values to simplify what must be specified in the user configuration.

public class Activator implements BundleActivator, ManagedService {

  public void start(BundleContext context) throws Exception {
    System.out.println("Sample bundle starting");
    // register to receive configuration
    ServiceRegistration<ManagedService> configRef = context.registerService(
      ManagedService.class,
      this,
      getDefaults()
      );
  }

  public void stop(BundleContext context) throws Exception {
    System.out.println("Sample bundle stopping");
    configRef.unregister();
  }

  Hashtable getDefaults() {
    Hashtable defaults = new Hashtable();
    defaults.put(org.osgi.framework.Constants.SERVICE_PID, "simpleBundle");
    return defaults;
  }

  public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
    if (properties != null)
    {
      String configColor = (String) properties.get("color");
      String configFlavor = (String) properties.get("flavor");
    }
  }

}
User configuration for the bundle can optionally be provided in the server.xml file, or an included file, by the following entry:
<simpleBundle color="red" flavor="raspberry" />
Note: The element name in the user configuration, simpleBundle matches the value of the org.osgi.framework.Constants.SERVICE_PID property used in the ManagedService registration.

For more advanced configuration use, see Describing configuration by using the OSGi Metatype service.