112 Declarative Services Specification

112.1 Introduction

The OSGi Framework contains a procedural service model which provides a publish/find/bind model for using services. This model is elegant and powerful, it enables the building of applications out of bundles that communicate and collaborate using these services.

This specification addresses some of the complications that arise when the OSGi service model is used for larger systems and wider deployments, such as:

  • Startup Time - The procedural service model requires a bundle to actively register and acquire its services. This is normally done at startup time, requiring all present bundles to be initialized with a Bundle Activator. In larger systems, this quickly results in unacceptably long startup times.

  • Memory Footprint - A service registered with the Framework implies that the implementation, and related classes and objects, are loaded in memory. If the service is never used, this memory is unnecessarily occupied. The creation of a class loader may therefore cause significant overhead.

  • Complexity - Service can come and go at any time. This dynamic behavior makes the service programming model more complex than more traditional models. This complexity negatively influences the adoption of the OSGi service model as well as the robustness and reliability of applications because these applications do not always handle the dynamicity correctly.

The service component model uses a declarative model for publishing, finding and binding to OSGi services. This model simplifies the task of authoring OSGi services by performing the work of registering the service and handling service dependencies. This minimizes the amount of code a programmer has to write; it also allows service components to be loaded only when they are needed. As a result, bundles need not provide a BundleActivator class to collaborate with others through the service registry.

From a system perspective, the service component model means reduced startup time and potentially a reduction of the memory footprint. From a programmer's point of view the service component model provides a simplified programming model.

The Service Component model makes use of concepts described in [1] Automating Service Dependency Management in a Service-Oriented Component Model.

112.1.1 Essentials

  • Backward Compatibility - The service component model must operate seamlessly with the existing service model.

  • Size Constraints - The service component model must not require memory and performance intensive subsystems. The model must also be applicable on resource constrained devices.

  • Delayed Activation - The service component model must allow delayed activation of a service component. Delayed activation allows for delayed class loading and object creation until needed, thereby reducing the overall memory footprint.

  • Simplicity - The programming model for using declarative services must be very simple and not require the programmer to learn a complicated API or XML sub-language.

  • Dependency Injection - The programming model for using declarative services supports three types of dependency injection: method injection, field injection, and constructor injection.

  • Reactive - It must be possible to react to changes in the external dependencies with different policies.

  • Annotations - Annotations must be provided that can leverage the type information to create the XML descriptor.

  • Introspection - It must be possible to introspect the service components.

112.1.2 Entities

  • Service Component - A service component contains a description that is interpreted at run time to create and dispose objects depending on the availability of other services, the need for such an object, and available configuration data. Such objects can optionally provide a service. This specification also uses the generic term component to refer to a service component.

  • Service Component Runtime (SCR) - The actor that manages the components and their life cycle and allows introspection of the components.

  • Component Description - The declaration of a service component. It is contained within an XML document in a bundle.

  • Component Properties - A set of properties which can be specified by the component description, Configuration Admin service and from the component factory.

  • Component Property Type - A user defined annotation type which defines component properties and is implemented by SCR to provide type safe access to the defined component properties.

  • Component Configuration - A component configuration represents a component description parameterized by component properties. It is the entity that tracks the component dependencies and manages a component instance. An activated component configuration has a component context.

  • Component Instance - An instance of the component implementation class. A component instance is created when a component configuration is activated and discarded when the component configuration is deactivated. A component instance is associated with exactly one component configuration.

  • Delayed Component - A component whose component configurations are activated when their service is requested.

  • Immediate Component - A component whose component configurations are activated immediately upon becoming satisfied.

  • Factory Component - A component whose component configurations are created and activated through the component's component factory.

  • Reference - A specified dependency of a component on a set of target services.

  • Target Services - The set of services that is defined by the reference interface and target property filter.

  • Bound Services - The set of target services that are bound to a component configuration.

  • Event methods - The bind, updated, and unbind methods associated with a Reference.

Figure 112.1 Service Component Runtime, org.osgi.service.component package

Service Component Runtime, org.osgi.service.component package

112.1.3 Synopsis

The Service Component Runtime reads component descriptions from started bundles. These descriptions are in the form of XML documents which define a set of components for a bundle. A component can refer to a number of services that must be available before a component configuration becomes satisfied. These dependencies are defined in the descriptions and the specific target services can be influenced by configuration information in the Configuration Admin service. After a component configuration becomes satisfied, a number of different scenarios can take place depending on the component type:

  • Immediate Component - The component configuration of an immediate component must be activated immediately after becoming satisfied. Immediate components may provide a service.

  • Delayed Component - When a component configuration of a delayed component becomes satisfied, SCR will register the service specified by the service element without activating the component configuration. If this service is requested, SCR must activate the component configuration creating an instance of the component implementation class that will be returned as the service object. If the scope attribute of the service element is bundle, then, for each distinct bundle that requests the service object, a different component configuration is created and activated and a new instance of the component implementation class is returned as the service object. If the scope attribute of the service element is prototype, then, for each distinct request for the service object, such as via ServiceObjects, a different component configuration is created and activated and a new instance of the component implementation class is returned as the service object.

  • Factory Component - If a component's description specifies the factory attribute of the component element, SCR will register a Component Factory service. This service allows client bundles to create and activate multiple component configurations and dispose of them. If the component's description also specifies a service element, then as each component configuration is activated, SCR will register it as a service.

112.1.4 Readers

  • Architects - The chapter, Components, gives a comprehensive introduction to the capabilities of the component model. It explains the model with a number of examples. The section about Component Life Cycle provides some deeper insight in the life cycle of components.

  • Service Programmers - Service programmers should read Components. This chapter should suffice for the most common cases. For the more advanced possibilities, they should consult Component Description for the details of the XML grammar for component descriptions.

  • Deployers - Deployers should consult Deployment.

112.2 Components

A component is a normal Java class contained within a bundle. The distinguishing aspect of a component is that it is declared in an XML document. Component configurations are activated and deactivated under the full control of SCR. SCR bases its decisions on the information in the component's description. This information consists of basic component information like the name and type, optional services that are implemented by the component, and references. References are dependencies that the component has on other services.

SCR must activate a component configuration when the component is enabled and the component configuration is satisfied and a component configuration is needed. During the life time of a component configuration, SCR can notify the component of changes in its bound references.

SCR will deactivate a previously activated component configuration when the component becomes disabled, the component configuration becomes unsatisfied, or the component configuration is no longer needed.

If an activated component configuration's configuration properties change, SCR must either notify the component configuration of the change, if the component description specifies a method to be notified of such changes, or deactivate the component configuration and then attempt to reactivate the component configuration using the new configuration information.

112.2.1 Declaring a Component

A component requires the following artifacts in the bundle:

  • An XML document that contains the component description.

  • The Service-Component manifest header which names the XML documents that contain the component descriptions.

  • An implementation class that is specified in the component description.

The elements in the component's description are defined in Component Description. The XML grammar for the component declaration is defined by the XML Schema, see Component Description Schema.

112.2.2 Immediate Component

An immediate component is activated as soon as its dependencies are satisfied. If an immediate component has no dependencies, it is activated immediately. A component is an immediate component if it is not a factory component and either does not specify a service or specifies a service and the immediate attribute of the component element set to true. If an immediate component configuration is satisfied and specifies a service, SCR must register the component configuration as a service in the service registry and then activate the component configuration.

For example, the bundle entry /OSGI-INF/activator.xml contains:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.activator"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.Activator"/>
</scr:component>

The manifest header Service-Component must also be specified in the bundle manifest. For example:

Service-Component: OSGI-INF/activator.xml

An example class for this component could look like:

public class Activator {
    public Activator() {...}
    private void activate(BundleContext context) {...}
    private void deactivate() {...}  
}

This example component is virtually identical to a Bundle Activator. It has no references to other services so it will be satisfied immediately. It publishes no service so SCR will activate a component configuration immediately.

The activate method is called when SCR activates the component configuration and the deactivate method is called when SCR deactivates the component configuration. If the activate method throws an Exception, then the component configuration is not activated and will be discarded.

112.2.3 Delayed Component

A delayed component specifies a service, is not specified to be a factory component and does not have the immediate attribute of the component element set to true. If a delayed component configuration is satisfied, SCR must register the component configuration as a service in the service registry but the activation of the component configuration is delayed until the registered service is requested. The registered service of a delayed component looks like a normal registered service but does not incur the overhead of an ordinarily registered service that require a service's bundle to be initialized to register the service.

For example, a bundle needs to see events of a specific topic. The Event Admin uses the white board pattern, receiving the events is therefore as simple as registering a Event Handler service. The example XML for the delayed component looks like:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.handler"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.HandlerImpl"/>
    <property name="event.topics">some/topic</property>
    <service> 
        <provide interface="org.osgi.service.event.EventHandler"/> 
    </service>
</scr:component>

The associated component class looks like:

public class HandlerImpl implements EventHandler{
    public void handleEvent(Event evt ) {
        ...
  }
}

The component configuration will only be activated once the Event Admin service requires the service because it has an event to deliver on the topic to which the component subscribed.

112.2.4 Factory Component

Certain software patterns require the creation of component configurations on demand. For example, a component could represent an application that can be launched multiple times and each application instance can then quit independently. Such a pattern requires a factory that creates the instances. This pattern is supported with a factory component. A factory component is used if the factory attribute of the component element is set to a factory identifier. This identifier can be used by a bundle to associate the factory with externally defined information.

SCR must register a Component Factory service on behalf of the component as soon as the component factory is satisfied. The service properties for the Component Factory service are the factory properties as specified by the factory-property and factory-properties elements of the component description. See Factory Property and Factory Properties Elements. The service properties of the Component Factory service must not include the component properties. SCR always adds the following factory properties, which cannot be overridden:

  • component.name - The name of the component.

  • component.factory - The factory identifier.

New configurations of the component can be created and activated by calling the newInstance method on this Component Factory service. The newInstance(Dictionary) method has a Dictionary object as a parameter. This Dictionary object is merged with the component properties as described in Component Properties. If the component specifies a service, then the service is registered after the created component configuration is satisfied with the component properties. Then the component configuration is activated.

For example, a component can provide a connection to a USB device. Such a connection should normally not be shared and should be created each time such a service is needed. The component description to implement this pattern looks like:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.factory"
    factory="usb.connection"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.USBConnectionImpl"/>
</scr:component>

The component class looks like:

public class USBConnectionImpl {
    private void activate(Map<String, ?> properties) {
     ...
    }
}

A factory component can be associated with a service. In that case, such a service is registered for each component configuration. For example, the previous example could provide a USB Connection service.

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.factory"    
    factory="usb.connection"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.USBConnectionImpl"/>
    <service>
        <provide interface="com.acme.usb.USBConnection"/>
    </service>
</scr:component>

The associated component class looks like:

public class USBConnectionImpl implements USBConnection {
    private void activate(Map<String, ?> properties) {...}
    public void connect() { ... }
    ...
    public void close() { ... }
}

A new service will be registered each time a new component configuration is created and activated with the newInstance method. This allows a bundle other than the one creating the component configuration to utilize the service. If the component configuration is deactivated, the service must be unregistered.

112.3 References to Services

Most bundles will require access to other services from the service registry. The dynamics of the service registry require care and attention of the programmer because referenced services, once acquired, could be unregistered at any moment. The component model simplifies the handling of these service dependencies significantly.

The services that are selected by a reference are called the target services. These are the services selected by the BundleContext.getServiceReferences method where the first argument is the reference's interface and the second argument is the reference's target property, which must be a valid filter.

A component configuration becomes satisfied when each specified reference is satisfied. A reference is satisfied if it specifies optional cardinality or when the number of target services is equal to or more than the minimum cardinality of the reference. An activated component configuration that becomes unsatisfied must be deactivated.

During the activation of a component configuration, SCR must bind some or all of the target services of a reference to the component configuration. Any target service that is bound to the component configuration is called a bound service. See Bound Services.

112.3.1 Accessing Services

A component instance must be able to use the services that are referenced by the component configuration, that is, the bound services of the references. The following techniques are available for a component instance to acquire these bound services:

  • Method injection - SCR calls a method on the component instance when a service becomes bound, when a service becomes unbound, or when its properties are updated. These methods are the bind, updated, and unbind methods specified by the reference. Method injection is useful if the component needs to be notified of changes to the bound services for a dynamic reference.

  • Field injection - SCR modifies a field in the component instance when a service becomes bound, when a service becomes unbound, or when its properties are updated.

  • Constructor injection - When SCR activates a component instance, the component instance must be constructed and constructor injection occurs. Bound services and activation objects can be parameters to the constructor.

  • Lookup strategy - A component instance can use one of the locateService methods of its ComponentContext to locate a bound service. These methods take the name of the reference as a parameter. If the reference has a dynamic policy, it is important to not store returned service objects but look them up every time they are needed.

A component may use multiple strategies to access the bound services of a reference.

112.3.2 Method Injection

When using method injection, SCR must call the component instance at the appropriate time. SCR must call on the following events:

  • bind - The bind method, if specified, is called to bind a new service to the component that matches the selection criteria. If the policy is dynamic then the bind method of a replacement service can be called before its corresponding unbind method.

  • updated - The updated method, if specified, is called when the service properties of a bound services are modified and the resulting properties do not cause the service to become unbound because it is no longer selected by the target property.

  • unbind - The unbind method, if specified, is called when SCR needs to unbind the service.

Each event is associated with an event method.

An event method can take one or more parameters. Each parameter must be of one of the following types:

  • <service-type> - The bound service object.

  • ServiceReference - A Service Reference for the bound service. This Service Reference may later be passed to the locateService(String,ServiceReference) method to obtain the actual service object. This approach is useful when the service properties need to be examined before accessing the service object. It also allows for the delayed activation of bound services when using method injection.

  • ComponentServiceObjects - A Component Service Objects for the bound service. This Component Service Objects can be used to obtain the actual service object or objects. This approach is useful when the referenced service has prototype service scope and the component instance needs multiple service objects for the service.

  • Map - An unmodifiable Map containing the service properties of the bound service. This Map must additionally implement Comparable with the compareTo method comparing service property maps using an ordering which is the same as the natural ordering of ServiceReferences as specified in ServiceReference.compareTo.

A suitable method is selected using the following priority. If the type specified by the reference's interface attribute is org.osgi.service.component.AnyService, then the parameter type must be java.lang.Object to match.

  1. The method takes a single parameter and the type of the parameter is org.osgi.framework.ServiceReference. This method will receive a Service Reference for the bound service.

  2. The method takes a single parameter and the type of the parameter is ComponentServiceObjects. This method will receive a Component Service Objects for the bound service.

  3. The method takes a single parameter and the type of the parameter is the type specified by the reference's interface attribute. This method will receive the bound service object.

  4. The method takes a single parameter and the type of the parameter is assignable from the type specified by the reference's interface attribute. If multiple methods match this rule, this implies the method name is overloaded and SCR may choose any of the methods to call. This method will receive the bound service object.

  5. The method takes a single parameter and the type of the parameter is java.util.Map. This method will receive an unmodifiable Map containing the service properties of the bound service.

  6. The method takes two or more parameters and the types of the parameters must be one of: the type specified by the reference's interface attribute, a type assignable from the type specified by the reference's interface attribute, org.osgi.framework.ServiceReference, ComponentServiceObjects, or java.util.Map. If multiple methods match this rule, this implies the method name is overloaded and SCR may choose any of the methods to call. In the case where the type specified by the reference's interface attribute is org.osgi.framework.ServiceReference, ComponentServiceObjects, or java.util.Map, the first parameter of that type will receive the bound service object. If selected event method has more than one parameter of that type, the remaining parameters of that type will receive a Service Reference for the bound service, a Service Objects for the bound service, or an unmodifiable Map containing the service properties of the bound service.

When searching for an event method to call, SCR must locate a suitable method as specified in Locating Component Methods and Fields. If no suitable method is located, SCR must log an error message with the Log Service, if present, and there will be no bind, updated, or unbind notification.

The bind and unbind methods must be called once for each bound service. This implies that if the reference has multiple cardinality, then the methods may be called multiple times. The updated method can be called multiple times per service.

In the following examples, a component requires the Logger Factory service. The first example uses the lookup strategy. The reference is declared without any bind, updated, and unbind methods:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.listen"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.LogLookupImpl"/>
    <reference name="LOG"
        interface="org.osgi.service.log.LoggerFactory"/>
</scr:component>

The component implementation class must now lookup the service. This looks like:

public class LogLookupImpl {
    private void activate(ComponentContext ctxt) {
        LoggerFactory lf = ctxt.locateService("LOG");
        lf.getLogger(LogLookupImpl.class).info("Hello Components!");
    }
}

Alternatively, the component could use method injection and ask to be notified with the Logger Factory service by declaring bind, updated, and unbind methods.

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.listen"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.LogEventImpl"/>
    <reference name="LOG"
        interface="org.osgi.service.log.LoggerFactory"
        bind="setLog"
        updated="updatedLog"
        unbind="unsetLog"
    />
</scr:component>

The component implementation class looks like:

public class LogEventImpl {
    LoggerFactory lf;
    Integer    level;
    void setLog( LoggerFactory l, Map<String,?> ref ) {
        lf = l;
        updatedLog(l, ref);
    }
    void updatedLog( LoggerFactory l, Map<String,?> ref) {
        level = (Integer) ref.get("level");
    }
    void unsetLog( LoggerFactory l ) { lf = null; }
    private void activate() {
        lf.getLogger(LogEventImpl.class).info("Hello Components!");
    }
}

Event methods can be declared private in the component class but are only looked up in the inheritance chain when they are protected, public, or have default access. See Locating Component Methods and Fields.

112.3.3 Field Injection

When using field injection, SCR must modify fields in the component instance at the appropriate time. SCR must modify the fields on the following events:

  • bind - The field is modified to bind a new service to the component that matches the selection criteria.

  • updated - For certain field types, the field is modified when the service properties of a bound services are modified and the resulting properties do not cause the service to become unbound because it is no longer selected by the target property.

  • unbind - The field is modified when SCR needs to unbind the service.

For a reference with unary cardinality, a field must be of one of the following types:

  • <service-type> - The bound service object. The type of the field can be the actual service type or it can be a type that is assignable from the actual service type. If the type specified by the reference's interface attribute is org.osgi.service.component.AnyService, then the actual service type is considered to be java.lang.Object.

  • ServiceReference - A Service Reference for the bound service. This Service Reference may later be passed to the locateService(String,ServiceReference) method to obtain the actual service object. This approach is useful when the service properties need to be examined before accessing the service object. It also allows for the delayed activation of bound services when using field injection.

  • ComponentServiceObjects - A Component Service Objects for the bound service. This Component Service Objects can be used to obtain the actual service object or objects. This approach is useful when the referenced service has prototype service scope and the component instance needs multiple service objects for the service.

  • Map - An unmodifiable Map containing the service properties of the bound service. This Map must additionally implement Comparable with the compareTo method comparing service property maps using an ordering which is the same as the natural ordering of ServiceReferences as specified in ServiceReference.compareTo.

  • Map.Entry - An unmodifiable Map.Entry whose key is an unmodifiable Map containing the service properties of the bound service, as above, and whose value is the bound service object. This Map.Entry must additionally implement Comparable with the compareTo method comparing the service property map key using an ordering which is the same as the natural ordering of ServiceReferences as specified in ServiceReference.compareTo.

  • Optional - An Optional holding one of the above types. The type of object held in the Optional is specified by the field-collection-type attribute in the component description. The Optional must be empty for an optional reference with no bound service.

If the actual service type is one of ServiceReference, ComponentServiceObjects, Map, Map.Entry, or Optional the field will be set to the service object rather than the object about the service.

For a reference with multiple cardinality, a field must be a collection of one of the following types:

  • Collection

  • List

  • A subtype of Collection - This type can only be used for dynamic references using the update reference field option. The component instance must initialize the field to a collection object in its constructor.

The type of objects set in the collection or the type of object held in the Optional is specified by the field-collection-type attribute in the component description:

  • service - The bound service object. This is the default field collection type.

  • reference - A Service Reference for the bound service.

  • serviceobjects - A Component Service Objects for the bound service.

  • properties - An unmodifiable Map containing the service properties of the bound service. This Map must implement Comparable, as above.

  • tuple - An unmodifiable Map.Entry whose key is an unmodifiable Map containing the service properties of the bound service, as above, and whose value is the bound service object. This Map.Entry must implement Comparable, as above.

Only instance fields of the field types above are supported. If a referenced field is declared with the static modifier or has a type other than one of the above, SCR must log an error message with the Log Service, if present, and the field must not be modified. SCR must locate a suitable field as specified in Locating Component Methods and Fields. If no suitable field is located, SCR must log an error message with the Log Service, if present, and no field will not be modified for the reference. If the bound service cannot be assigned to the field because the type is unassignable, SCR must log an error message containing the exception with the Log Service, if present, and no field will not be modified for the reference.

Care must be taken by the component implementation regarding the field. SCR has no way to know if the component implementation itself may alter the field value. The component implementation should not alter the field value and allow SCR to manage it. SCR must treat the field as if the component implementation does not alter the field value so SCR may retain its own copy of the value set in the field.

In the following examples, a component requires the Logger Factory service.

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.listen"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.LogEventImpl"/>
    <reference name="LOG"
        interface="org.osgi.service.log.LoggerFactory"
        field="lf"
    />
</scr:component>

The component implementation class looks like:

public class LogEventImpl {
    LoggerFactory lf;
    private void activate() {
        lf.getLogger(LogEventImpl.class).info("Hello Components!");
    }
}

Fields can be declared private in the component class but are only looked up in the inheritance chain when they are protected, public, or have default access. See Locating Component Methods and Fields.

112.3.4 Constructor Injection

When using constructor injection, SCR must construct the component instance using the appropriate constructor passing activation objects and bound services as parameters. Since a component instance is only constructed once, constructor parameters for references must be for static references.

A suitable constructor is selected using the following steps:

  1. If the constructor is not public, then the constructor must not be considered.

  2. If the constructor has a parameter count that does not match the value of the init attribute in the component element, then the constructor must not be considered. If the value of the init attribute is 0, the default value, then the public no-parameter constructor must be used.

  3. For the constructor parameters associated with a reference, that is, there is a reference with a parameter attribute whose value matches the zero-based parameter number of the constructor parameter, if the parameter type is not one of the types supported for field injection for a static reference, then the constructor must not be considered. See Field Injection for information on types supported for field injection.

  4. For the constructor parameters not associated with a reference, if the parameter type is not assignable from one of the activation object types, then the constructor must not be considered. See Activation Objects for information on activation object types.

  5. If only a single constructor remains, this constructor must be used to construct the component instance.

  6. If more than one constructor remains, this implies the constructor is overloaded and SCR may choose any of the remaining constructors to construct the component instance.

When searching for the constructor to call, SCR must use reflection on the implementation class. If no suitable constructor is located, SCR must log an error message with the Log Service, if present, and the component configuration is not activated.

If the constructor throws an exception, SCR must log an error message containing the exception with the Log Service, if present, and the component configuration is not activated. If the bound service cannot be assigned to the constructor parameter because the type is unassignable, SCR must log an error message containing the exception with the Log Service, if present, and the component configuration is not activated.

If the constructor parameter is associated with a reference having cardinality of 0..1 and there is no bound service for the reference, then the value null will be supplied as the constructor parameter.

In the following examples, a component requires the Logger Factory service.

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.listen" init="1"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.LogEventImpl"/>
    <reference name="LOG"
        interface="org.osgi.service.log.LoggerFactory"
        parameter="0"
    />
</scr:component>

The component implementation class looks like:

public class LogEventImpl {
    public LogEventImpl(LoggerFactory lf) {
        lf.getLogger(LogEventImpl.class).info("Hello Components!");
    }
}

112.3.5 Reference Cardinality

A component implementation is always written with a certain cardinality for each reference in mind. The cardinality represents two important concepts:

  • Multiplicity - Does the component implementation assume a single service or does it explicitly handle multiple services? For example, when a component uses the Logger Factory service, it only needs to bind to one Logger Factory service to function correctly. Alternatively, when the Configuration Admin uses the Configuration Listener services it needs to bind to all target services present in the service registry to dispatch its events correctly.

  • Optionality - Can the component function without any bound service present? Some components can still perform useful tasks even when no service is available; other components must bind to at least one service before they can be useful. For example, the Configuration Admin in the previous example must still provide its functionality even if there are no Configuration Listener services present. Alternatively, an application that registers a Servlet with the Http Service has little to do when the Http Service is not present, it should therefore use a reference with a mandatory cardinality.

The cardinality is expressed with the following syntax:

cardinality  ::= optionality '..' multiplicity
optionality  ::= '0' | '1'
multiplicity ::= '1' | 'n'

The cardinality for a reference can be specified as one of four choices:

  • 0..1 - Optional and unary.

  • 1..1 - Mandatory and unary (Default) .

  • 0..n - Optional and multiple.

  • 1..n - Mandatory and multiple.

The minimum cardinality is specified by the optionality part of the cardinality. This is either 0 or 1. A minimum cardinality property can be used to raise the minimum cardinality of a reference from this initial value. For example, a 0..n cardinality in the component description can be raised into a 3..n cardinality at runtime by setting the minimum cardinality property for the reference to 3. This would typically be done by a deployer setting the minimum cardinality property in a configuration for the component. The minimum cardinality for a unary cardinality cannot exceed 1. See Minimum Cardinality Property for more information.

A reference is satisfied if the number of target services is equal to or more than the minimum cardinality. The multiplicity is irrelevant for the satisfaction of the reference. The multiplicity only specifies if the component implementation is written to handle being bound to multiple services (n) or requires SCR to select and bind to a single service (1).

When a satisfied component configuration is activated, there must be at most one bound service for each reference with a unary cardinality and at least as many bound services as the minimum cardinality for each reference. If the cardinality constraints cannot be maintained after a component configuration is activated, that is the reference becomes unsatisfied, the component configuration must be deactivated. If the reference has a unary cardinality and there is more than one target service for the reference, then the bound service must be the target service whose ServiceReference is first in the ranking order as specified in ServiceReference.compareTo.

In the following example, a component wants to register a resource with all Http Services that are available. Such a scenario has the cardinality of 0..n. The code must be prepared to handle multiple calls to the bind method for each Http Service in such a case. In this example, the code uses the registerResources method to register a directory for external access.

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.listen"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.HttpResourceImpl"/>
    <reference name="HTTP"
        interface="org.osgi.service.http.HttpService"
        cardinality="0..n"
        bind="setPage"
        unbind="unsetPage"
    />
</scr:component>

public class HttpResourceImpl {
    private void setPage(HttpService http) {
        http.registerResources("/scr", "scr", null );
    }
    private void unsetPage(HttpService http) {
        http.unregister("/scr");
    }
}

112.3.6 Reference Scope

A component implementation must be written to understand the service scope of referenced services. The reference scope defines whether the component expects the bundle to be exposed to a single service object for a bound service or to potentially multiple services objects. The following reference scopes are available:

  • bundle - For all references to a given bound service, all activated component instances within a bundle must use the same service object. That is, for a given bound service, all component instances within a bundle will be using the same service object. This is the default reference scope.

  • prototype - For all references to a given bound service, each activated component instance may use a single, distinct service object. That is, for a given bound service, each component instance may use a distinct service object but within a component instance all references to the bound service will use the same service object.

  • prototype_required - For all references to a given bound service, each activated component instance must use a single, distinct service object. That is, for a given bound service, each component instance will use a distinct service object but within a component instance all references to the bound service will use the same service object.

For a bound service of a reference with bundle reference scope, SCR must get the service object from the OSGi Framework's service registry using the getService method on the component's Bundle Context. If the service object for a bound service has been obtained and the service becomes unbound, SCR must unget the service object using the ungetService method on the component's Bundle Context and discard all references to the service object. This ensures that the bundle will only be exposed to a single instance of the service object at any given time.

For a bound service of a reference with prototype or prototype_required reference scope, SCR must use a Service Objects object obtained from the OSGi Framework's service registry using the component's Bundle Context to get any service objects. If service objects for a bound service have been obtained and the service becomes unbound, SCR must unget any unreleased service objects using the Service Objects object obtained from the OSGi Framework's service registry using the component's Bundle Context. This means that if a component instance used a Component Service Objects object to obtain service objects, SCR must track those service objects so that when the service becomes unbound, SCR can unget any unreleased service objects.

Additionally, for a reference with prototype_required reference scope, only services registered with prototype service scope can be considered as target services. This ensures that each component instance can be exposed to a single, distinct instance of the service object. Using prototype_required reference scope effectively adds service.scope=prototype to the target property for the reference. A service that does not use prototype service scope cannot be used as a bound service for a reference with prototype_required reference scope since the service cannot provide a distinct service object for each component instance.

112.3.7 Reference Policy

Once all the references of a component are satisfied, a component configuration can be activated and therefore bound to target services. However, the dynamic nature of the OSGi service registry makes it likely that services are registered, modified and unregistered after target services are bound. These changes in the service registry could make one or more bound services no longer a target service thereby making obsolete any object references that the component has to these service objects. Components therefore must specify a policy how to handle these changes in the set of bound services. A policy-option can further refine how changes affect bound services.

112.3.7.1 Static Reference Policy

The static policy is the most simple policy and is the default policy. A reference with a static policy is called a static reference. A component instance never sees any of the dynamics of the static reference. The bind method is called and/or the field is set before the component instance is activated. Static references can also be used for parameters for constructor injection. Component configurations are deactivated before any bound service for the static reference becomes unavailable. If a target service is available to replace the bound service which became unavailable, the component configuration must be reactivated and the replacement service is bound to the new component instance.

If the policy-option is reluctant then the registration of an additional target service for a reference must not result in deactivating and reactivating a component configuration. If the policy-option is greedy then the component configuration must be reactivated when new applicable services become available. See Table 112.1 on page .

If a static reference specifies an updated method and the bound service's properties change, SCR must call the updated method.

The static policy can be very expensive if it depends on services that frequently unregister and re-register or if the cost of activating and deactivating a component configuration is high. Static policy is usually also not applicable if the cardinality specifies multiple bound services.

112.3.7.2 Dynamic Reference Policy

The dynamic policy is slightly more complex since the component implementation must properly handle changes in the set of bound services that can occur on any thread at any time after the component instance is created. A reference with a dynamic policy is called a dynamic reference. With a dynamic reference, SCR can change the set of bound services without deactivating a component configuration. If the component uses method injection to access services, then the component instance will be notified of changes in the set of bound services by calls to the bind, updated, and unbind methods.

If the policy-option is reluctant then a bound reference is not rebound even if a more suitable service becomes available for a 1..1 or 0..1 reference. If the policy-option is greedy then the component must be unbound and rebound for that reference. See Table 112.1 on page .

The previous example with the registering of a resource directory used a static policy. This implied that the component configurations are deactivated when there is a change in the bound set of Http Services. The code in the example can be seen to easily handle the dynamics of Http Services that come and go. The component description can therefore be updated to:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.listen"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.HttpResourceImpl"/>
    <reference name="HTTP"
        interface="org.osgi.service.http.HttpService"
        cardinality="0..n"
        policy="dynamic"
        bind="setPage"
        unbind="unsetPage"
    />
</scr:component>

The code is identical to the previous example.

112.3.8 Reference Policy Option

The reference policy option defines how eager the reference is to rebind when a new, potentially a higher ranking, target service becomes available. The reference policy option can have the following values:

  • reluctant - Minimize rebinding and reactivating. This is the default reference policy option.

  • greedy - Maximize the use of the best service by deactivating static references or rebinding dynamic references.

Table 112.1 defines the actions that are taken when a better target service becomes available. In this context, better is when the reference is not bound or when the new target service has a higher ranking than the bound service.

Table 112.1 Action taken for policy-option when a new or higher ranking service becomes available

Cardinality static reluctant static greedy dynamic reluctant dynamic greedy
0..1

Ignore

Reactivate to bind the better target service.

If no service is bound, bind to new target service. Otherwise, ignore new target service.

If no service is bound, bind to better target service. Otherwise, unbind the bound service and bind the better target service.

1..1

Ignore

Reactivate to bind the better target service.

Ignore

Unbind the bound service, then bind the new service.

0..n

Ignore

Reactivate

Bind new target service

Bind new target service

1..n

Ignore

Reactivate

Bind new target service

Bind new target service


112.3.9 Reference Field Option

For a reference using field injection, the reference field option defines how SCR must manage the field value. The reference field option can have the following values:

  • replace - SCR must set the field value. Any field value set by the constructor of the component instance is overwritten. This is the default reference field option.

  • update - SCR must update the collection set in the field. This collection can be set by the constructor of the component instance. This reference field option can only be used for a dynamic reference with multiple cardinality.

For a static reference, the replace option must be used.

For a dynamic reference, the choice of reference field option is influenced by the cardinality of the reference. For unary cardinality, the replace option must be used. For multiple cardinality, either the replace or update option can be used.

If the update option is used when not permitted, SCR must log an error message with the Log Service, if present, and the field must not be modified.

112.3.9.1 Replace Field Option

If the field is declared with the final modifier, SCR must log an error message with the Log Service, if present, and the field must not be modified.

For a static reference, SCR must set the field value before the component instance is activated and must not change the field while the component is active. This means there is a happens-before relationship between setting the field and activating the component instance, so the active component can safely read the field.

For a dynamic reference, the field must be declared with the volatile modifier so that field value changes made by SCR are visible to other threads. If the field is not declared with the volatile modifier, SCR must log an error message with the Log Service, if present, and the field must not be modified.

For a reference with unary cardinality, SCR must set the field value with initial bound service, if any, before the component instance is activated. If the reference has optional cardinality and there is no bound service, SCR must set the field value to null. If the reference is dynamic, when there is a new bound service or the service properties of the bound service are modified and the field holds service properties, SCR must replace the field value. If the reference has optional cardinality and there is no bound service, SCR must set the field value to null.

For a reference with multiple cardinality, the type of the field must be Collection or List. If the field has a different type, SCR must log an error message with the Log Service, if present, and the field must not be modified. Before the component instance is activated, SCR must set the field value with a new mutable collection that must contain the initial set of bound services sorted using an ordering which is the same as the natural ordering of ServiceReferences as specified in ServiceReference.compareTo. The collection may be empty if the reference has optional cardinality and there are no bound services. If the reference is dynamic, when there is a change in the set of bound services or the service properties of a bound service are modified and the collection holds service properties, SCR must replace the field value with a new mutable collection that must contain the updated set of bound services sorted using an ordering which is the same as the natural ordering of ServiceReferences as specified in ServiceReference.compareTo. The new collection may be empty if the reference has optional cardinality and there are no bound services.

112.3.9.2 Update Field Option

The update option can only be used for a dynamic reference with multiple cardinality. The component's constructor can set the field with its choice of collection implementation. In this case, the field can be declared with the final modifier. The collection implementation used by the component should use identity rather than equals or hashCode to manage the elements of the collection. The collection implementation should also be thread-safe since SCR may update the collection from threads different than those used by the component instance.

After constructing the component instance, if the field value is null:

  • If the type of the field is Collection or List, SCR will set the field value to a new mutable empty collection or list object, respectively. If the field is declared with the final modifier, SCR must log an error message with the Log Service, if present, and the field must not be modified.

  • Otherwise, SCR must log an error message with the Log Service, if present, and the field must not be modified.

SCR must not change the field value while the component is active and only update the contents of the collection. SCR must update the collection before the component instance is activated by calling Collection.add for each bound service. When there is a change to the set of bound services:

  • SCR must call Collection.add for a newly bound service.

  • SCR must call Collection.remove for an unbound service.

  • If the service properties of a bound service are modified and the collection holds service properties, SCR must call Collection.add for the replacement element followed by Collection.remove for the old element.

The collection may be empty if the reference has optional cardinality and there are no bound services.

112.3.10 Selecting Target Services

The target services for a reference are constrained by the reference's interface name and target property. By specifying a filter in the target property, the programmer and deployer can constrain the set of services that should be part of the target services.

For example, a component wants to track all Component Factory services that have a factory identification of acme.application. The following component description shows how this can be done.

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.listen"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.FactoryTracker"/>
    <reference name="FACTORY"
        interface=
            "org.osgi.service.component.ComponentFactory"
        target="(component.factory=acme.application)"
    />
</scr:component>

The filter is manifested as a component property called the target property. The target property can also be set by property and properties elements, see Property and Properties Elements. The deployer can also set the target property by establishing a configuration for the component which sets the value of the target property. This allows the deployer to override the target property in the component description. See Target Property for more information.

112.3.10.1 Any Service Type

A special exception to the selecting of target services is the use of the special interface name org.osgi.service.component.AnyService. This means that a service type is not used to select the target services and just the target property is used to select the target services. When the special interface name of org.osgi.service.component.AnyService is used, a target property must be present to constrain the target services to some subset of all available services. If no target property is present, SCR must log an error message with the Log Service, if present, and the reference cannot be satisfied. Note that there may be performance impacts resulting from a target property matching too broad a set of target services. A target property of (service.id=*) is valid but will match all services in the service registry which will likely be neither very useful nor performant.

The reference member or parameter must have a service type of java.lang.Object to allow SCR to provide any service object.

For example, a component wants to track all Jakarta RESTful Web Services Extension services. Jakarta RESTful Web Services Extension services can be registered under many different service types but must be registered with the service property osgi.jakartars.extension=true. The following component description shows how this can be done.

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="jakartars.extension.listener"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.ExtensionListener"/>
    <reference name="EXTENSIONS"
        interface=
            "org.osgi.service.component.AnyService"
        target="(osgi.jakartars.extension=true)"
        cardinality="0..n"
    />
</scr:component>

112.3.11 Circular References

It is possible for a set of component descriptions to create a circular dependency. For example, if component A references a service provided by component B and component B references a service provided by component A then a component configuration of one component cannot be satisfied without accessing a partially activated component instance of the other component. SCR must ensure that a component instance is never accessible to another component instance or as a service until it has been fully activated, that is it has returned from its activate method if it has one.

Circular references must be detected by SCR when it attempts to satisfy component configurations and SCR must fail to satisfy the references involved in the cycle and log an error message with the Log Service, if present. However, if one of the references in the cycle has optional cardinality SCR must break the cycle. The reference with the optional cardinality can be satisfied and bound to zero target services. Therefore the cycle is broken and the other references may be satisfied.

112.3.12 Logger Support

SCR provides special support for components having references to the Logger Factory from the Log Service specification. If the reference uses method, field or constructor injection, the referenced service is of type org.osgi.service.log.LoggerFactory, and the type of the parameter or field to receive the service object is of type org.osgi.service.log.Logger or org.osgi.service.log.FormatterLogger, then SCR must obtain the proper type of Logger from the bound Logger Factory service and use the obtained Logger as the service object rather than the service object for the bound Logger Factory service.

To obtain the Logger object to use as the service object, SCR must call the LoggerFactory.getLogger(Bundle bundle, String name, Class loggerType) method passing the bundle declaring the component as the first argument, the fully qualified name of the component implementation class as the second argument, and the type of the parameter or field, org.osgi.service.log.Logger or org.osgi.service.log.FormatterLogger, as the third argument.

For example, the following code will have the logger field set to a Logger object created by SCR from the bound Logger Factory service.

@Component
public class MyComponent {
  @Reference(service=LoggerFactory.class)
  private Logger logger;
  @Activate
  void activate(ComponentContext context) {
    logger.trace(“activating component id {}”,
      context.getProperties().get(“component.id”));
  }
}

112.3.13 Satisfying Condition

The Condition Service Specification in OSGi Core Release 8 defines Condition services representing a particular state at runtime and requires the OSGi Framework to always register the True Condition service.

Every component description is defined to have a reference to a satisfying condition. The name of this reference must be osgi.ds.satisfying.condition. If a component description does not explicitly declare a reference with the name osgi.ds.satisfying.condition, SCR must augment the component description to add the following implicit reference as the last reference:

<reference name="osgi.ds.satisfying.condition"
    interface="org.osgi.service.condition.Condition"
    target="(osgi.condition.id=true)"
    policy="dynamic"
/>

The implicit reference is handled in the same manner as any explicit reference in the component description, including handling reference properties. See Reference Properties. In order for a component configuration to be satisfied, the reference for the satisfying condition, like all other references, must be satisfied. The target property for the reference to the satisfying condition, osgi.ds.satisfying.condition.target, can be used to select the satisfying condition. This allows a component configuration to be configured to select which Condition service is the satisfying condition. The implicit reference defaults to the target property value of (osgi.condition.id=true) which targets the True Condition, that is always registered by the OSGi Framework, and thus the implicit reference, using the default target property value, can always be satisfied.

For example, you can use the SatisfyingConditionTarget component property type to set the target property for the reference to the satisfying condition to select a condition indicating that some subsystem needed by the component is ready.

@Component
@SatisfyingConditionTarget("(osgi.condition.id=my.subsystem.ready)")
public class MyComponent {
  ...
}

A component's satisfying condition can be used as a way to control, via the configuration of component properties, whether a component configuration can be satisfied. That is, it can be a way to "enable" or "disable" a component configuration through its configuration. See Condition Service Specification of OSGi Core Release 8 for additional information on Conditions.

SCR must support the satisfying condition for all components even those with component descriptions in older namespaces.

112.4 Component Description

Component descriptions are defined in XML documents contained in a bundle and any attached fragments.

If SCR detects an error when processing a component description, it must log an error message with the Log Service, if present, and ignore the component description. Errors can include XML parsing errors and ill-formed component descriptions.

112.4.1 Annotations

A number of CLASS retention annotations have been provided to allow tools to construct the component description XML from the Java class files. These annotations will be discussed with the appropriate elements and attributes. Since the naming rules between XML and Java differ, some name changes are necessary.

Multi-word element and attribute names that use a minus sign ('-' \u002D) are changed to camel case. For example, the configuration-pid attribute in the component element is the configurationPid member in the @Component annotation. The annotation class that corresponds to an element starts with an upper case letter. For example the component element is represented by the @Component annotation.

Some elements do not have a corresponding annotation since the annotations can be parameterized by the type information in the Java class. For example, the @Component annotation synthesizes the implement element's class attribute from the type it is applied to.

See Component Annotations for more information.

112.4.2 Service Component Header

XML documents containing component descriptions must be specified by the Service-Component header in the manifest. The value of the header is a comma separated list of paths to XML entries within the bundle.

Service-Component ::= header // See Common Header Syntax in Core

The Service-Component header has no architected directives or properties. The header can be left empty.

The last component of each path in the Service-Component header may use wildcards so that Bundle.findEntries can be used to locate the XML document within the bundle and its fragments. For example:

Service-Component: OSGI-INF/*.xml

A Service-Component manifest header specified in a fragment is ignored by SCR. However, XML documents referenced by a bundle's Service-Component manifest header may be contained in attached fragments.

SCR must process each XML document specified in this header. If an XML document specified by the header cannot be located in the bundle and its attached fragments, SCR must log an error message with the Log Service, if present, and continue.

112.4.3 XML Document

A component description must be in a well-formed XML document, [4] Extensible Markup Language (XML) 1.0, stored in a UTF-8 encoded bundle entry. The namespace for component descriptions is:

http://www.osgi.org/xmlns/scr/v1.5.0

The recommended prefix for this namespace is scr. This prefix is used by examples in this specification. XML documents containing component descriptions may contain a single, root component element or one or more component elements embedded in a larger document. Use of the namespace for component descriptions is mandatory. The attributes and sub-elements of a component element are always unqualified.

If an XML document contains a single, root component element which does not specify a namespace, then the http://www.osgi.org/xmlns/scr/v1.0.0 namespace is assumed. Component descriptions using the http://www.osgi.org/xmlns/scr/v1.0.0 namespace must be treated according to version 1.0 of this specification.

SCR must parse all component elements in the namespace. Elements not in this namespace must be ignored. Ignoring elements that are not recognized allows component descriptions to be embedded in any XML document. For example, an entry can provide additional information about components. These additional elements are parsed by another sub-system.

See Component Description Schema for component description schema.

112.4.4 Component Element

The component element specifies the component description. The following text defines the structure of the XML grammar using a form that is similar to the normal grammar used in OSGi specifications. In this case the grammar should be mapped to XML elements:

<component> ::= (<property> | <properties>)*
                <service>?
                <reference>*
                <implementation>

SCR must not require component descriptions to specify the elements in the order listed above and as required by the XML schema. SCR must allow other orderings since arbitrary orderings of these elements do not affect the meaning of the component description. Only the relative ordering of property and properties elements and of reference elements have meaning.

The component element has the attributes and @Component annotations defined in the following table.

Table 112.2 Component Element and Annotations

Attribute Annotation Description
name name

The name of a component must be unique within a bundle. The component name is used as a PID to retrieve component properties from the OSGi Configuration Admin service if present, unless a configuration-pid attribute has been defined. See Deployment for more information. If the component name is used as a PID then it should be unique within the framework. The XML schema allows the use of component names which are not valid PIDs. Care must be taken to use a valid PID for a component name if the component should be configured by the Configuration Admin service. This attribute is optional. The default value of this attribute is the value of the class attribute of the nested implementation element. If multiple component elements in a bundle use the same value for the class attribute of their nested implementation element, then using the default value for this attribute will result in duplicate component names. In this case, this attribute must be specified with a unique value.

enabled enabled

Controls whether the component is enabled when the bundle is started. The default value is true. If enabled is set to false, the component is disabled until the method enableComponent is called on the ComponentContext object. This allows some initialization to be performed by some other component in the bundle before this component can become satisfied. See Enabled.

factory factory

If set to a non-empty string, it indicates that this component is a factory component. SCR must register a Component Factory service for each factory component. See Factory Component.

immediate immediate

Controls whether component configurations must be immediately activated after becoming satisfied or whether activation should be delayed. The default value is false if the factory attribute or if the service element is specified and true otherwise. If this attribute is specified, its value must be false if the factory attribute is also specified or must be true unless the service element is also specified.

configuration-policy

configurationPolicy

OPTIONAL

REQUIRE

IGNORE

Controls whether component configurations must be satisfied depending on the presence of a corresponding Configuration object in the OSGi Configuration Admin service. A corresponding configuration is a Configuration object where the PID is the name of the component.

  • optional - (default) Use the corresponding Configuration object if present but allow the component to be satisfied even if the corresponding Configuration object is not present.

  • require - There must be a corresponding Configuration object for the component configuration to become satisfied.

  • ignore - Always allow the component configuration to be satisfied and do not use the corresponding Configuration object even if it is present.

configuration-pid configurationPid

The configuration PIDs to be used for the component in conjunction with Configuration Admin. Multiple configuration PIDs can be specified by using a whitespace separated list in the attribute. The default value for this attribute is the name of the component.

The annotation uses a String[] to specify multiple configuration PIDs. The order in which configuration PIDs are specified must be preserved in the generated component description. The annotation can also use the special configuration PID name "$" to specify the name of the component. This special name must be replaced with the actual name of the component in the generated component description.

activate Activate

Specifies the name of the method to call when a component configuration is activated. The default value of this attribute is activate. See Activate Method for more information.

The Activate annotation must be applied to at most one method which is to be used as the activate method.

activation-fields Activate

Specifies the whitespace separated list of the names of the fields to hold activation objects. The fields are set once after the constructor has been called and before calling any other method on the fully constructed component instance such as the activate method. See Activation Objects for more information.

The Activate annotation will use the name of the field to which it is applied as the activation field name.

init Activate

Specifies the number of arguments of the public constructor to use. The default is 0 which represents the public no-parameter constructor. See Constructor Injection for more information.

The Activate annotation must be applied to at most one constructor which is to be used as the constructor for component instances.

deactivate Deactivate

Specifies the name of the method to call when a component configuration is deactivated. The default value of this attribute is deactivate. See Deactivate Method for more information.

The Deactivate annotation must be applied to at most one method which is to be used as the deactivate method.

modified Modified

Specifies the name of the method to call when the configuration properties for a component configuration is using a Configuration object from the Configuration Admin service and that Configuration object is modified without causing the component configuration to become unsatisfied. If this attribute is not specified, then the component configuration will become unsatisfied if its configuration properties use a Configuration object that is modified in any way. See Modified Method for more information.

The Modified annotation must be applied to at most one method which is to be used as the modified method.


112.4.5 Implementation Element

The implementation element is required and defines the name of the component implementation class. The single attribute is defined in the following table.

Table 112.3 Implementation Element and Annotations

Attribute Annotation Description
class Component

The Java fully qualified name of the implementation class.

The component Component annotation will define the implementation element automatically from the type it is applied to.


The class is retrieved with the loadClass method of the component's bundle. The class must have a public constructor with the correct parameter count and types which will be used to construct the component instance.

If the component description specifies a service, the class must implement all interfaces that are provided by the service.

112.4.6 Property and Properties Elements

A component description can define a number of properties. These can be defined inline or from a resource in the bundle. The property and properties elements can occur multiple times and they can be interleaved. This interleaving is relevant because the properties are processed from top to bottom. Later properties override earlier properties that have the same name.

Properties can also be overridden by a Configuration Admin service's Configuration object before they are exposed to the component or used as service properties. This is described in Component Properties and Deployment.

The property element has the attributes and annotations defined in the following table.

Table 112.4 Property Element and Annotations

Attribute Annotation Description
name

Component property

The name of the property.

value

The value of the property. This value is parsed according to the property type. If the value attribute is specified, the body of the element is ignored. If the type of the property is not String, parsing of the value is done by the static valueOf(String) method in the given type. For Character types, the conversion must be handled by Integer.valueOf method, a Character is always represented by its Unicode value.

type

The type of the property. Defines how to interpret the value. The type must be one of the following Java types:

  • String (default)

  • Long

  • Double

  • Float

  • Integer

  • Byte

  • Character

  • Boolean

  • Short

<body>

If the value attribute is not specified, the body of the property element must contain one or more values. The value of the property is then an array of the specified type. The result will be translated to an array of primitives or Strings. For example, if the type attribute specifies Integer, then the resulting array must be int[].

Values must be placed one per line and blank lines are ignored. Parsing of each value is done by the parse methods in the class identified by the type, after trimming the line of any beginning and ending white space. Each String value is also trimmed of beginning and ending white space.


For example, a component that needs an array of hosts can use the following property definition:

<property name="hosts">
        www.acme.com
        backup.acme.com
</property>

This property declaration results in the property hosts, with a value of String[] { "www.acme.com", "backup.acme.com" }.

A property can also be set with the property annotation element of Component. This element is an array of strings that must follow the following syntax:

property ::= name ( ':' type )? '=' value

In this case name, type, and value parts map to the attributes of the property element. If multiple values must be specified then the same name can be repeated multiple times. For example:

@Component(property={"foo:Integer=1","foo:Integer=2","foo:Integer=3"})
public class FooImpl {
  ...
}

The properties element references an entry in the bundle whose contents conform to a standard [3] Java Properties File.

At runtime, SCR reads the entry to obtain the properties and their values. The properties element attributes are defined in the following table.

Table 112.5 Properties Element and Annotations

Attribute Annotation Description
entry

Component properties

The entry path relative to the root of the bundle


For example, to include vendor identification properties that are stored in the OSGI-INF directory, the following definition could be used:

<properties entry="OSGI-INF/vendor.properties"/>

The properties annotation element of Component can be used to provide the same information. This element consists of an array of strings where each string defines an entry. The order within the array is the order that must be used for the XML. However, the annotations do not support interleaving of the generated property and properties elements.

For example:

@Component(properties="OSGI-INF/vendor.properties")

See Ordering of Generated Component Properties for more information on the ordering of generated properties when using annotations.

112.4.7 Service Element

The service element is optional. It describes the service information to be used when a component configuration is to be registered as a service.

A service element has the following attribute defined in the following table.

Table 112.6 Service Element and Annotations

Attribute Annotation Description
scope

Component scope

SINGLETON

BUNDLE

PROTOTYPE

Controls the scope of the provided service. If set to singleton, when the component is registered as a service, it must be registered as a bundle scope service but only a single component configuration must be created and activated and a new instance of the component implementation class of the component must be used for all bundles using the service. If set to bundle, when the component is registered as a service, it must be registered as a bundle scope service and a different component configuration is created and activated and a new instance of the component implementation class must be created for each bundle using the service. If set to prototype, when the component is registered as a service, it must be registered as a prototype scope service and a different component configuration is created and activated and a new instance of the component implementation class must be created for each distinct request for the service, such as via ServiceObjects.


The scope attribute must be singleton if the component is a factory component or an immediate component. This is because SCR is not free to create component configurations as necessary to support non-singleton scoped services. A component description is ill-formed if it specifies that the component is a factory component or an immediate component and scope is not singleton.

The service element must have one or more provide elements that define the service interfaces. The provide element has the attribute defined in the following table.

Table 112.7 Provide Element and Annotations

Attribute Annotation Description
interface

Component service

The name of the interface that this service is registered under. This name must be the fully qualified name of a Java class. For example, org.osgi.service.eventadmin.EventHandler. The specified Java class should be an interface rather than a class, however specifying a class is supported. The component implementation class must implement all the specified service interfaces.

The Component annotation can specify the provided services, if this element is not specified all directly implemented interfaces on the component's type are defined as service interfaces. Specifying an empty array indicates that no service should be registered.


For example, a component implements an Event Handler service.

<service>
    <provide interface=
        "org.osgi.service.eventadmin.EventHandler"/>
</service>

This previous example can be generated with the following annotation:

@Component
public class Foo implements EventHandler { ... }

112.4.8 Reference Element

A reference declares a dependency that a component has on a set of target services. A component configuration is not satisfied, unless all its references are satisfied. A reference specifies target services by specifying their interface and an optional target property.

A reference element has the attributes defined in the following table.

Table 112.8 Reference Element and Annotations

Attribute Annotation Description
name

name

The name of the reference. This name is local to the component and can be used to locate a bound service of this reference with one of the locateService methods of ComponentContext. Each reference element within the component must have a unique name. This name attribute is optional. The default value of this attribute is the value of the interface attribute of this element. If multiple reference elements in the component use the same interface name, then using the default value for this attribute will result in duplicate reference names. In this case, this attribute must be specified with a unique name for the reference to avoid an error.

The Reference annotation will use the name of the annotated method, field, or parameter as the default reference name. If the method name begins with bind, set or add, that prefix is removed.

interface

service

Fully qualified name of the class that is used by the component to access the service. The service provided to the component must be type compatible with this class. That is, the component must be able to cast the service object to this class. A service must be registered under this name to be considered for the set of target services.

The Reference annotation will use the type of the first parameter of the annotated method or the type of the annotated parameter or field to determine the service value.

The special org.osgi.service.component.AnyService service name can be used to indicate that the service type name is not used to select target services. Only the target property is used to select target services. When using this special service name, the reference field or parameter must be of type java.lang.Object so that any service object can be provided. See Any Service Type.

cardinality

cardinality

MANDATORY

OPTIONAL

MULTIPLE

AT_LEAST_ONE

Specifies if the reference is optional and if the component implementation support a single bound service or multiple bound services. See Reference Cardinality.

policy

policy

STATIC

DYNAMIC

The policy declares the assumption of the component about dynamicity. See Reference Policy.

policy-option

policyOption

RELUCTANT

GREEDY

Defines the policy when a better service becomes available. See Reference Policy.

target

target

An optional OSGi Framework filter expression that further constrains the set of target services. The default is no filter, limiting the set of matched services to all service registered under the given reference interface. The value of this attribute is used for the value of the target property of the reference. See Target Property.

scope

scope

BUNDLE

PROTOTYPE

PROTOTYPE_

 REQUIRED

The reference scope for this reference. See Reference Scope.

bind

Reference

bind

The name of a method in the component implementation class that is used to notify that a service is bound to the component configuration. For static references, this method is only called before the activate method. For dynamic references, this method can also be called while the component configuration is active. See Accessing Services.

The Reference annotation will use the name of the method it is applied to as the bind method name.

updated

updated

The name of a method in the component implementation class that is used to notify that a bound service has modified its properties.

unbind

unbind

Same as bind, but is used to notify the component configuration that the service is unbound. For static references, the method is only called after the deactivate method. For dynamic references, this method can also be called while the component configuration is active. See Accessing Services.

field

Reference

field

The name of a field in the component implementation class that is used to hold service(s) that are bound to the component configuration. For static references, this field is set once after the constructor has been called and before calling the activate method. For dynamic references, this field can modified while the component configuration is active. See Accessing Services.

The Reference annotation will use the name of the field it is applied to as the field name.

field-option

fieldOption

REPLACE

UPDATE

Defines how the field value must be managed. This is ignored if the field attribute is not set. See Reference Field Option.

field-collection-type

collectionType

SERVICE

REFERENCE

SERVICEOBJECTS

PROPERTIES

TUPLE

Defines the types of elements in the collection or Optional referenced by the field value or constructor parameter. This is ignored if the field attribute or parameter attribute is not set. It is also ignored when the field attribute or parameter attribute is set, the cardinality is unary, and the field or constructor parameter type is not Optional. See Field Injection for more information.

The Reference annotation can generally infer the value of the collection elements from the generic type information of the annotated field or constructor parameter but it can be explicitly defined if needed.

parameter

Reference

parameter

The zero-based parameter number of a parameter in the constructor of the component that is used to receive service(s) that are bound to the component configuration. If this attribute is set and the policy attribute is set to DYNAMIC, this attribute must be ignored and SCR must log an error message with the Log Service, if present. See Accessing Services.

The Reference annotation will use the zero-based parameter number of the parameter it is applied to as the parameter number.


In the generated component description, the reference elements must be ordered in ascending lexicographical order, using String.compareTo, of the names of the references.

The following code demonstrates the use of the Reference annotation for method injection.

@Component
public class FooImpl implements Foo {
  @Reference( 
    policy = DYNAMIC, 
    policyOption = GREEDY,
    cardinality = MANDATORY )
  void setLog( LoggerFactory lf ) { ... }
  void unsetLog( LoggerFactory lf ) { ... }
  void updatedLog( Map<String,?> ref ) { ... }

  @Activate
  void open() { ... }
  @Deactivate
  void close() { ... }
}

The following code demonstrates the use of the Reference annotation for field injection.

@Component
public class FooImpl implements Foo {
  @Reference
  volatile LoggerFactory lf;

  @Activate
  void open() { lf.getLogger(FooImpl.class).info("activated"); }
  @Deactivate
  void close() { lf.getLogger(FooImpl.class).info("deactivated"); }
}

The following code demonstrates the use of the Reference annotation for constructor injection.

@Component
public class FooImpl implements Foo {
  private final Logger logger;

  @Activate
  public FooImpl( @Reference LoggerFactory lf ) {
    logger = lf.getLogger(FooImpl.class);
  }

  @Activate
  void open() { logger.info("activated"); }
  @Deactivate
  void close() { logger.info("deactivated"); }
}

For a reference to be used with the lookup strategy, there are no bind methods or fields to annotate with the Reference annotation. Instead Reference annotations can be specified in the reference element of the Component annotation. When used in this way, the name and service elements must be specified since there is no annotated member from which the name or service can be determined. The following code demonstrates the use of the Reference annotation for the lookup strategy.

@Component( reference = 
  @Reference( name = "log", service = LoggerFactory.class )
)
public class FooImpl implements Foo {
  @Activate
  void open( ComponentContext context ) {
    LoggerFactory lf = context.locateService( "log" );
    ...
  }
  @Deactivate
  void close() { ... }
}

112.4.9 Factory Property and Factory Properties Elements

If the component is a factory component, see Factory Component, the component description can define a number of factory properties. These can be defined inline or from a resource in the bundle. The factory-property and factory-properties elements can occur multiple times and they can be interleaved. This interleaving is relevant because the factory properties are processed from top to bottom. Later factory properties override earlier factory properties that have the same name.

The factory-property element has the attributes and annotations defined in the following table.

Table 112.9 Factory Property Element and Annotations

Attribute Annotation Description
name

Component factoryProperty

The name of the factory property.

value

The value of the factory property. This value is parsed according to the property type. If the value attribute is specified, the body of the element is ignored. If the type of the factory property is not String, parsing of the value is done by the static valueOf(String) method in the given type. For Character types, the conversion must be handled by Integer.valueOf method, a Character is always represented by its Unicode value.

type

The type of the factory property. Defines how to interpret the value. The type must be one of the following Java types:

  • String (default)

  • Long

  • Double

  • Float

  • Integer

  • Byte

  • Character

  • Boolean

  • Short

<body>

If the value attribute is not specified, the body of the factory-property element must contain one or more values. The value of the factory property is then an array of the specified type. The result will be translated to an array of primitives or Strings. For example, if the type attribute specifies Integer, then the resulting array must be int[].

Values must be placed one per line and blank lines are ignored. Parsing of each value is done by the parse methods in the class identified by the type, after trimming the line of any beginning and ending white space. Each String value is also trimmed of beginning and ending white space.


A factory property can also be set with the factoryProperty annotation element of Component. This element is an array of strings that must follow the following syntax:

factory-property ::= name ( ':' type )? '=' value

In this case name, type, and value parts map to the attributes of the factory-property element. If multiple values must be specified then the same name can be repeated multiple times.

The factory-properties element references an entry in the bundle whose contents conform to a standard [3] Java Properties File.

At runtime, SCR reads the entry to obtain the factory properties and their values. The factory-properties element attributes are defined in the following table.

Table 112.10 Factory Properties Element and Annotations

Attribute Annotation Description
entry

Component factoryProperties

The entry path relative to the root of the bundle


For example, to include properties that are stored in the OSGI-INF directory, the following definition could be used:

<factory-properties entry="OSGI-INF/factory.properties"/>

The factoryProperties annotation element of Component can be used to provide the same information. This element consists of an array of strings where each string defines an entry. The order within the array is the order that must be used for the XML. However, the annotations do not support interleaving of the generated factory-property and factory-properties elements.

For example:

@Component(factoryProperties="OSGI-INF/factory.properties")

When using annotation elements to specify factory properties, a tool processing the Component annotations must write the defined factory properties into the generated component description in the following order.

  1. factoryProperty element of the Component annotation.

  2. factoryProperties element of the Component annotation.

112.5 Component Life Cycle

112.5.1 Enabled

A component must first be enabled before it can be used. A component cannot be enabled unless the component's bundle is started. See Starting Bundles in OSGi Core Release 8. All components in a bundle become disabled when the bundle is stopped. So the life cycle of a component is contained within the life cycle of its bundle.

Every component can be enabled or disabled. The initial enabled state of a component is specified in the component description via the enabled attribute of the component element. See Component Element. Component configurations can be created, satisfied and activated only when the component is enabled.

The enabled state of a component can be controlled with the Component Context enableComponent(String) and disableComponent(String) methods. The purpose of later enabling a component is to be able to decide programmatically when a component can become enabled. For example, an immediate component can perform some initialization work before other components in the bundle are enabled. The component descriptions of all other components in the bundle can be disabled by having enabled set to false in their component descriptions. After any necessary initialization work is complete, the immediate component can call enableComponent to enable the remaining components.

The enableComponent and disableComponent methods must return after changing the enabled state of the named component. Any actions that result from this, such as activating or deactivating a component configuration, must occur asynchronously to the method call. Therefore a component can disable itself.

All components in a bundle can be enabled by passing a null as the argument to enableComponent.

112.5.2 Satisfied

Component configurations can only be activated when the component configuration is satisfied. A component configuration becomes satisfied when the following conditions are all satisfied:

  • The component is enabled.

  • If the component description specifies configuration-policy=required, then a Configuration object for the component is present in the Configuration Admin service.

  • Using the component properties of the component configuration, all the component's references are satisfied. A reference is satisfied when the reference specifies optional cardinality or the number of target services is equal to or more than the minimum cardinality of the reference.

Once any of the listed conditions are no longer true, the component configuration becomes unsatisfied. An activated component configuration that becomes unsatisfied must be deactivated.

112.5.3 Immediate Component

A component is an immediate component when it must be activated as soon as its dependencies are satisfied. Once the component configuration becomes unsatisfied, the component configuration must be deactivated. If an immediate component configuration is satisfied and specifies a service, SCR must register the component configuration as a service in the service registry and then activate the component configuration. The service properties for this registration consist of the component properties as defined in Service Properties.

The state diagram is shown in Figure 112.2.

Figure 112.2 Immediate Component Configuration

Immediate Component Configuration

112.5.4 Delayed Component

A key attribute of a delayed component is the delaying of class loading and object creation. Therefore, the activation of a delayed component configuration does not occur until there is an actual request for a service object. A component is a delayed component when it specifies a service but it is not a factory component and does not have the immediate attribute of the component element set to true.

SCR must register a service after the component configuration becomes satisfied. The registration of this service must look to observers of the service registry as if the component's bundle actually registered this service. This makes it possible to register services without creating a class loader for the bundle and loading classes, thereby allowing reduction in initialization time and a delay in memory footprint.

When SCR registers the service on behalf of a component configuration, it must avoid causing a class load to occur from the component's bundle. SCR can ensure this by registering a ServiceFactory object with the Framework for that service. By registering a ServiceFactory object, the actual service object is not needed until the ServiceFactory is called to provide the service object. The service properties for this registration consist of the component properties as defined in Service Properties.

The activation of a component configuration must be delayed until its service is requested. When the service is requested, if the service has the scope attribute set to bundle, SCR must create and activate a unique component configuration for each bundle requesting the service. If the service has the scope attribute set to prototype, SCR must create and activate a unique component configuration for each distinct request for the service. Otherwise, if the service has the scope attribute set to singleton, SCR must activate a single component configuration which is used by all requests for the service. A component instance can determine the bundle it was activated for by calling the getUsingBundle() method on the Component Context.

The activation of delayed components is depicted in a state diagram in Figure 112.3. Notice that multiple component configurations can be created from the REGISTERED state if a delayed component specifies a service scope set to a value other than singleton.

If the service has the scope attribute set to prototype, SCR must deactivate a component configuration when it stops being used as a service object since the component configuration must not be reused as a service object. If the service has the scope attribute set to singleton or bundle, SCR must deactivate a component configuration when it stops being used as a service object after a delay since the component configuration may be reused as a service object in the near future. This allows SCR implementations to reclaim component configurations not in use while attempting to avoid deactivating a component configuration only to have to quickly activate a new component configuration for a new service request. The delay amount is implementation specific and may be zero.

Figure 112.3 Delayed Component Configuration

Delayed Component Configuration

112.5.5 Factory Component

SCR must register a Component Factory service as soon as the component factory becomes satisfied. The component factory is satisfied when the following conditions are all satisfied:

  • The component is enabled.

  • Using the component properties specified by the component description, all the component's references are satisfied. A reference is satisfied when the reference specifies optional cardinality or there is at least one target service for the reference.

The component factory, however, does not use any of the target services and does not bind to them.

Once any of the listed conditions are no longer true, the component factory becomes unsatisfied and the Component Factory service must be unregistered. Any component configurations activated via the component factory are unaffected by the unregistration of the Component Factory service, but may themselves become unsatisfied for the same reason.

The Component Factory service must be registered under the name org.osgi.service.component.ComponentFactory with the following service properties:

  • component.name - The name of the component.

  • component.factory - The value of the factory attribute.

The service properties of the Component Factory service must not include the component properties.

New component configurations are created and activated when the newInstance method of the Component Factory service is called. If the component description specifies a service, the component configuration is registered as a service under the provided interfaces. The service properties for this registration consist of the component properties as defined in Service Properties. The service registration must take place before the component configuration is activated. Service unregistration must take place before the component configuration is deactivated.

Figure 112.4 Factory Component

Factory Component

A Component Factory service has a single method: newInstance(Dictionary). This method must create, satisfy and activate a new component configuration and register its component instance as a service if the component description specifies a service. It must then return a ComponentInstance object. This ComponentInstance object can be used to get the component instance with the getInstance() method.

SCR must attempt to satisfy the component configuration created by newInstance before activating it. If SCR is unable to satisfy the component configuration given the component properties and the Dictionary argument to newInstance, the newInstance method must throw a ComponentException.

The client of the Component Factory service can also deactivate a component configuration with the dispose() method on the ComponentInstance object. If the component configuration is already deactivated, or is being deactivated, then this method is ignored. Also, if the component configuration becomes unsatisfied for any reason, it must be deactivated by SCR.

Once a component configuration created by the Component Factory has been deactivated, that component configuration will not be reactivated or used again.

112.5.6 Activation

Activating a component configuration consists of the following steps:

  1. Load the component implementation class.

  2. Compute the bound services. See Bound Services.

  3. Create the component context. See Component Context.

  4. Construct the component instance. See Constructor Injection.

  5. Set the activation fields, if any. See Activation Objects.

  6. Bind the bound services. See Binding Services.

  7. Call the activate method, if any. See Activate Method. Calling the activate method signals the completion of activating the component instance.

Component instances must never be reused. Each time a component configuration is activated, SCR must create a new component instance to use with the activated component configuration. A component instance must complete activation before it can be deactivated. Once the component configuration is deactivated or fails to activate due to an exception, SCR must unbind all the component's bound services and discard all references to the component instance associated with the activation.

112.5.7 Bound Services

When a component configuration's reference is satisfied, there is a set of zero or more target services for that reference. When the component configuration is activated, a subset of the target services for each reference are bound to the component configuration. The subset is chosen by the cardinality of the reference. See Reference Cardinality.

Obtaining the service object for a bound service may result in activating a component configuration of the bound service which could result in an exception. If the loss of the bound service due to the exception causes the reference's cardinality constraint to be violated, then activation of this component configuration will fail. Otherwise the bound service which failed to activate will be considered unbound.

112.5.8 Component Context

The Component Context can be made available to a component instance during activation, modification, and deactivation. It provides the interface to the execution context of the component, much like the Bundle Context provides a bundle the interface to the Framework. A Component Context should therefore be regarded as a capability and not shared with other components or bundles.

Each distinct component instance receives a unique Component Context. Component Contexts are not reused and must be discarded when the component configuration is deactivated.

112.5.9 Activation Objects

A component can have an activate method, activation fields, and also receive activation objects via its constructor.

The following activation object types are supported:

  • ComponentContext - The Component Context for the component configuration.

  • BundleContext - The Bundle Context of the component's bundle.

  • Map - An unmodifiable Map containing the component properties.

  • A component property type - An instance of the component property type which allows type safe access to component properties defined by the component property type. See Component Property Types.

For activation fields, only instance fields of the activation object types above are supported. If an activation field is declared with the static modifier or has a type other than one of the above, SCR must log an error message with the Log Service, if present, and the field must not be modified. SCR must locate a suitable field as specified in Locating Component Methods and Fields. If no suitable field is located for an activation field name, SCR must log an error message with the Log Service, if present.

112.5.10 Binding Services

When binding services, the references are processed in the order in which they are specified in the component description. That is, target services from the first specified reference are bound before services from the next specified reference.

If the reference uses field injection, the field must be set. Then, if the reference uses method injection, the bind method must be called for each bound service of that reference. If a bind method throws an exception, SCR must log an error message containing the exception with the Log Service, if present, but the activation of the component configuration does not fail.

112.5.11 Activate Method

A component can have an activate method. The name of the activate method can be specified by the activate attribute. If the activate attribute is not specified, the default method name of activate is used. See Component Element.

The activate method can take zero or more parameters. Each parameter must be assignable from one of the activation object types. A suitable method is selected using the following priority:

  1. The method takes a single parameter and the type of the parameter is org.osgi.service.component.ComponentContext.

  2. The method takes a single parameter and the type of the parameter is org.osgi.framework.BundleContext.

  3. The method takes a single parameter and the type of the parameter is a component property type.

  4. The method takes a single parameter and the type of the parameter is java.util.Map.

  5. The method takes two or more parameters and the type of each parameter must be one of the activation object types. If multiple methods match this rule, this implies the method name is overloaded and SCR may choose any of the methods to call.

  6. The method takes zero parameters.

When searching for the activate method to call, SCR must locate a suitable method as specified in Locating Component Methods and Fields. If the activate attribute is specified and no suitable method is located, SCR must log an error message with the Log Service, if present, and the component configuration is not activated.

If an activate method is located, SCR must call this method to complete the activation of the component configuration. If the activate method throws an exception, SCR must log an error message containing the exception with the Log Service, if present, and the component configuration is not activated.

112.5.12 Bound Service Replacement

If an active component configuration has a dynamic reference with unary cardinality and the bound service is modified or unregistered and ceases to be a target service, or the policy-option is greedy and a better target service becomes available then SCR must attempt to replace the bound service with a new bound service.

If the reference uses field injection, the field must be set for the replacement bound service. Then, if the reference uses method injection, SCR must first bind the new bound service and then unbind the outgoing service. This reversed order allows the component to not have to handle the inevitable gap between the unbind and bind methods. However, this means that in the unbind method care must be taken to not overwrite the newly bound service. For example, the following code handles the associated concurrency issues and simplify handling the reverse order.

final AtomicReference<LogService> log = new AtomicReference<LogService>();

void setLogService( LogService log ) {
    this.log.set(log);
}
void unsetLogService( LogService log ) {
    this.log.compareAndSet(log, null);
}

If the dynamic reference falls below the minimum cardinality, the component configuration must be deactivated because the cardinality constraints will be violated.

If a component configuration has a static reference and a bound service is modified or unregistered and ceases to be a target service, or the policy-option is greedy and a better target service becomes available then SCR must deactivate the component configuration. Afterwards, SCR must attempt to activate the component configuration again if another target service can be used as a replacement for the outgoing service.

112.5.13 Updated

If an active component is bound to a service that modifies its service properties then the component can be updated. If the reference uses field injection and the field holds the service properties, the field must be set for the updated bound service. Then, if the reference uses method injection and specifies an updated method, the updated method must be called.

112.5.14 Modification

Modifying a component configuration can occur if the component description specifies the modified attribute and the component properties of the component configuration use a Configuration object from the Configuration Admin service and that Configuration object is modified without causing the component configuration to become unsatisfied. If this occurs, the component instance will be notified of the change in the component properties.

If the modified attribute is not specified, then the component configuration will become unsatisfied if its component properties use a Configuration object and that Configuration object is modified in any way.

Modifying a component configuration consists of the following steps:

  1. Update the component context for the component configuration with the modified configuration properties.

  2. Call the modified method. See Modified Method.

  3. Modify the bound services for the dynamic references if the set of target services changed due to changes in the target properties. See Bound Service Replacement.

  4. If the component configuration is registered as a service, modify the service properties.

A component instance must complete activation, or a previous modification, before it can be modified.

See Configuration Changes for more information.

112.5.15 Modified Method

The name of the modified method is specified by the modified attribute. See Component Element.

The modified method can take zero or more parameters. Each parameter must be assignable from one of the activation object types. A suitable method is selected using the following priority:

  1. The method takes a single parameter and the type of the parameter is org.osgi.service.component.ComponentContext.

  2. The method takes a single parameter and the type of the parameter is org.osgi.framework.BundleContext.

  3. The method takes a single parameter and the type of the parameter is a component property type.

  4. The method takes a single parameter and the type of the parameter is java.util.Map.

  5. The method takes two or more parameters and the type of each parameter must be one of the activation object types. If multiple methods match this rule, this implies the method name is overloaded and SCR may choose any of the methods to call.

  6. The method takes zero parameters.

SCR must locate a suitable method as specified in Locating Component Methods and Fields. If the modified attribute is specified and no suitable method is located, SCR must log an error message with the Log Service, if present, and the component configuration becomes unsatisfied and is deactivated as if the modified attribute was not specified.

If a modified method is located, SCR must call this method to notify the component configuration of changes to the component properties. If the modified method throws an exception, SCR must log an error message containing the exception with the Log Service, if present and continue processing the modification.

112.5.16 Deactivation

Deactivating a component configuration consists of the following steps:

  1. Call the deactivate method, if present. See Deactivate Method.

  2. Unbind any bound services. See Unbinding.

  3. Release all references to the component instance and component context.

A component instance must complete activation or modification before it can be deactivated. A component configuration can be deactivated for a variety of reasons. The deactivation reason can be received by the deactivate method. The following reason values are defined:

Once the component configuration is deactivated, SCR must discard all references to the component instance and component context associated with the activation.

112.5.17 Deactivate Method

A component instance can have a deactivate method. The name of the deactivate method can be specified by the deactivate attribute. See Component Element. If the deactivate attribute is not specified, the default method name of deactivate is used. Activation fields must not be modified during deactivation.

The deactivate method can take zero or more parameters. Each parameter must be assignable from one of the following types:

  • One of the activation object types.

  • int or Integer - The reason the component configuration is being deactivated. See Deactivation.

A suitable method is selected using the following priority:

  1. The method takes a single parameter and the type of the parameter is org.osgi.service.component.ComponentContext.

  2. The method takes a single parameter and the type of the parameter is org.osgi.framework.BundleContext.

  3. The method takes a single parameter and the type of the parameter is a component property type.

  4. The method takes a single parameter and the type of the parameter is java.util.Map.

  5. The method takes a single parameter and the type of the parameter is int.

  6. The method takes a single parameter and the type of the parameter is java.lang.Integer.

  7. The method takes two or more parameters and the type of each parameter must be one of the activation object types, int or java.lang.Integer. If multiple methods match this rule, this implies the method name is overloaded and SCR may choose any of the methods to call.

  8. The method takes zero parameters.

When searching for the deactivate method to call, SCR must locate a suitable method as specified in Locating Component Methods and Fields. If the deactivate attribute is specified and no suitable method is located, SCR must log an error message with the Log Service, if present, and the deactivation of the component configuration will continue.

If a deactivate method is located, SCR must call this method to commence the deactivation of the component configuration. If the deactivate method throws an exception, SCR must log an error message containing the exception with the Log Service, if present, and the deactivation of the component configuration will continue.

112.5.18 Unbinding

When a component configuration is deactivated, the bound services are unbound from the component configuration.

When unbinding services, the references are processed in the reverse order in which they are specified in the component description. That is, target services from the last specified reference are unbound before services from the previous specified reference.

If the reference uses method injection, the unbind method must be called for each bound service of that reference. If an unbind method throws an exception, SCR must log an error message containing the exception with the Log Service, if present, and the deactivation of the component configuration will continue. Then, if the reference uses field injection, the field must be set to null.

112.5.19 Life Cycle Example

A component could declare a dependency on the Http Service to register some resources.

<?xml version="1.0" encoding="UTF-8"?>
<scr:component name="example.binding"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
    <implementation class="com.acme.impl.Binding"/>
    <reference name="LOG"
        interface="org.osgi.service.log.LogService"
        cardinality="1..1"
        policy="static"
    />   
    <reference name="HTTP"
        interface="org.osgi.service.http.HttpService"
        cardinality="0..1"
        policy="dynamic"
        bind="setHttp"
        unbind="unsetHttp"
    />
</scr:component>

The component implementation code looks like:

public class Binding {
    LogService  log;
    HttpService http;

    private void setHttp(HttpService h) {
        http = h;
        // register servlet
    }
    private void unsetHttp(HttpService h){
        if (http == h)
            http = null;
        // unregister servlet
    }
    private void activate(ComponentContext context ) {
        log = (LogService) context.locateService("LOG");
    }
    private void deactivate(ComponentContext context ) {...}
}

This example is depicted in a sequence diagram in Figure 112.5 with the following scenario:

  1. A bundle with the example.Binding component is started. At that time there is a Log Service l1 and a Http Service h1 registered.

  2. The Http Service h1 is unregistered

  3. A new Http Service h2 is registered

  4. The Log Service h1 is unregistered.

Figure 112.5 Sequence Diagram for binding

Sequence Diagram for binding

112.6 Component Properties

Each component configuration is associated with a set of component properties. The component properties are specified in the following configuration sources (in order of precedence):

  1. Properties specified in the argument of the ComponentFactory.newInstance method. This is only applicable for factory components.

  2. Properties retrieved from the OSGi Configuration Admin service in Configuration objects whose PID matches a configuration PID. The configuration PIDs are specified by the configuration-pid attribute of the component element. See Component Element. If no configuration-pid attribute is specified, the component name is used as the default configuration PID. If multiple configuration PIDs are specified, the order of precedence follows the order the configuration PIDs are specified in the component description. That is, the precedence for the configuration for an earlier specified configuration PID is lower than the precedence for the configurations for a later specified configuration PID.

  3. Properties specified in the component description via property and properties elements. Properties specified later in the component description override properties that have the same name specified earlier. See Property and Properties Elements.

  4. Target properties specified in the component description via the target attribute of reference elements. See Target Property. The value of the target attribute is used for the value of a target property.

The precedence behavior allows certain default values to be specified in the component description while allowing properties to be replaced and extended by:

  • A configuration in Configuration Admin

  • The argument to the ComponentFactory.newInstance method

Normally, a property value from a higher precedence configuration source replace a property value from a lower precedence configuration source. However, the service.pid property values receive different treatment. For the service.pid property, if the property appears multiple times in the configuration sources, SCR must aggregate all the values found into a Collection<String> having an iteration order such that the first item in the iteration is the property value from the lowest precedence configuration source and the last item in the iteration is the property value from the highest precedence configuration source. If the component description specifies multiple configuration PIDs, then the order of the service.pid property values from the corresponding configurations matches the order the configuration PIDs are specified in the component description. The values of the service.pid component property are the values as they come from the configuration sources which, for Configuration objects, may be more detailed than the configuration PIDs specified in the component description.

SCR always adds the following component properties, which cannot be overridden:

  • component.name - The component name.

  • component.id - A unique value ( Long) that is larger than all previously assigned values. These values are not persistent across restarts of SCR.

112.6.1 Service Properties

When SCR registers a service on behalf of a component configuration, SCR must follow the recommendations in Property Propagation and must not propagate private configuration properties. That is, the service properties of the registered service must be all the component properties of the component configuration whose property names do not start with full stop ('.' \u002E).

Component properties whose names start with full stop are available to the component instance but are not available as service properties of the registered service.

112.6.2 Reference Properties

This specification defines some component properties which are associated with specific component references. These are called reference properties. The name of a reference property for a reference is the name of the reference appended with a full stop ('.' \u002E) and a suffix unique to the reference property. Reference properties can be set wherever component properties can be set.

All component property names starting with a reference name followed by a full stop ('.' \u002E) are reserved for use by this specification.

Following are the reference properties defined by this specification.

112.6.2.1 Target Property

The target property is a reference property which aids in the selection of target services for the reference. See Selecting Target Services. The name of a target property is the name of a reference appended with .target. For example, the target property for a reference with the name http would have the name http.target. The value of a target property is a filter string used to select targets services for the reference.

The target property for a reference can also be set by the target attribute of the reference element. See Reference Element.

112.6.2.2 Minimum Cardinality Property

The initial minimum cardinality of a reference is specified by the optionality: the first part of the cardinality. It is either 0 or 1. The minimum cardinality of a reference cannot exceed the multiplicity: the second part of the cardinality. See Reference Cardinality for more information on the cardinality of a reference.

The minimum cardinality property is a reference property which can be used to raise the minimum cardinality of a reference from its initial value. That is, a 0..1 cardinality can be raised to a 1..1 cardinality by setting the reference's minimum cardinality property to 1, and a 0..n or 1..n cardinality can be raised to a m..n cardinality by setting the reference's minimum cardinality property to m such that m is a positive integer. The minimum cardinality of a reference cannot be lowered. That is, a 1..1 or 1..n cardinality cannot be lowered to a 0..1 or 0..n cardinality because the component was coded to expect at least one bound service.

The name of a minimum cardinality property is the name of a reference appended with .cardinality.minimum. For example, the minimum cardinality property for a reference with the name http would have the name http.cardinality.minimum. The value of a minimum cardinality property must be a positive integer or a value that can be coerced into a positive integer. See Coercing Component Property Values for information on coercing property values. If the numerical value of the minimum cardinality property is not valid for the reference's cardinality or the minimum cardinality property value cannot be coerced into a numerical value, then the minimum cardinality property must be ignored.

SCR must support the minimum cardinality property for all components even those with component descriptions in older namespaces.

112.7 Deployment

A component description contains default information to select target services for each reference. However, when a component is deployed, it is often necessary to influence the target service selection in a way that suits the needs of the deployer. Therefore, SCR uses Configuration objects from Configuration Admin to replace and extend the component properties for a component configuration. That is, through Configuration Admin, a deployer can configure component properties.

A component's configuration PIDs are used as keys for obtaining additional component properties from Configuration Admin. When matching a configuration PID to a Configuration object, SCR must use the Configuration object with the best matching PID for the component's bundle. See Targeted PIDs for more information on targeted PIDs and Extenders and Targeted PIDs for more information on selecting the Configuration object with the best matching PID.

The following situations can arise when looking for Configuration objects:

  • No Configuration - If the component's configuration-policy is set to ignore or there are no Configurations with a PID or factory PID matching any of the configuration PIDs, then component configurations will not obtain component properties from Configuration Admin. Only component properties specified in the component description or via the ComponentFactory.newInstance method will be used.

  • Not Satisfied - If the component's configuration-policy is set to require and, for each configuration PID, there is no Configuration with a matching PID or factory PID, then the component configuration is not satisfied and will not be activated.

  • Single Configuration - If none of the configuration PIDs matches a factory PID, then component configurations will obtain additional component properties from Configuration Admin.

  • Factory Configuration - If one of the configuration PIDs matches a factory PID, with zero or more Configurations, then for each Configuration of the factory PID, a component configuration must be created that will obtain additional component properties from Configuration Admin.

    It is a configuration error if more than one of the configuration PIDs match a factory PID and SCR must log an error message with the Log Service, if present. If the configuration-policy is set to optional, the component configuration must be satisfied without the configurations PIDs which match a factory PID. If the configuration-policy is set to require, the component configuration is not satisfied and will not be activated.

    A factory configuration must not be used if the component is a factory component. This is because SCR is not free to create component configurations as necessary to support multiple Configurations. When SCR detects this condition, it must log an error message with the Log Service, if present, and ignore the component description.

SCR must obtain the Configuration objects from the Configuration Admin service using the Bundle Context of the bundle containing the component. SCR must only use Configuration objects for which the bundle containing the component has visibility. See Location Binding.

To ensure Configuration Plugins can participate in the configuration process, SCR must use the Configuration.getProcessedProperties method when obtaining the configuration data from a Configuration object. To use the getProcessedProperties method, SCR must supply a Service Reference for a ManagedService or ManagedServiceFactory service. The ManagedService or ManageServiceFactory service must be registered using the Bundle Context of the bundle containing the component. If SCR registers one of these services for the purpose of using the service's Service Reference for the call to getProcessedProperties, SCR should register the service without a service.pid service property so that the service itself is not called by Configuration Admin.

For example, there is a component named com.acme.client with a reference named HTTP that requires an Http Service which must be bound to a component com.acme.httpserver which provides an Http Service. A deployer can establish the following configuration:

[PID=com.acme.client, factoryPID=null]
HTTP.target = (component.name=com.acme.httpserver)

112.7.1 Configuration Changes

SCR must track changes in the Configuration objects matching the configuration PIDs of a component description. Changes include the creating, updating and deleting of Configuration objects matching the configuration PIDs. The actions SCR must take when a configuration change for a component configuration occurs are based upon how the configuration-policy and modified attributes are specified in the component description, whether a component configuration becomes satisfied, remains satisfied or becomes unsatisfied and the type and number of matching Configuration objects.

With targeted PIDs, multiple Configuration objects can exist which can match a configuration PID. Creation of a Configuration object with a better matching PID than a Configuration object currently being used by a component configuration results in a configuration change for the component configuration with the new Configuration object replacing the currently used Configuration object. Deletion of a Configuration object currently being used by a component configuration when there is another Configuration object matching the configuration PID also results in a configuration change for the component configuration with the Configuration object having the best matching PID replacing the currently used, and now deleted, Configuration object.

112.7.1.1 Ignore Configuration Policy

For configuration-policy of ignore, component configurations are unaffected by configuration changes since the component properties do not include properties from Configuration objects.

112.7.1.2 Require Configuration Policy

For configuration-policy of require, component configurations require a Configuration object for each specified configuration PID. With a factory configuration, there can be zero or more matching Configuration objects which will result in a component configuration for each Configuration object of the factory configuration. With a factory component, multiple component configurations can be created all using the matching Configuration objects.

A configuration change can cause a component configuration to become unsatisfied if any of the following occur:

  • Each configuration PID of the component description does not have a matching Configuration object.

  • A target property change results in a bound service of a static reference ceasing to be a target service.

  • A target property change results in unbound target services for a static reference with the greedy policy option.

  • A target property change or minimum cardinality property change results in a reference falling below the minimum cardinality.

  • The component description does not specify the modified attribute.

112.7.1.3 Optional Configuration Policy

For configuration-policy of optional, component configurations do not require Configuration objects. Since matching Configuration objects are optional, component configurations can be satisfied with zero or more matched configuration PIDs. If a Configuration object is then created which matches a configuration PID, this is a configuration change for the component configurations that are not using the created Configuration object. If a Configuration object is deleted which matches a configuration PID, this is a configuration change for the component configurations using the deleted Configuration object.

Furthermore, with a factory configuration matching a configuration PID, the factory configuration can provide zero or more Configuration objects which will result in a component configuration for each Configuration object or a single component configuration when zero matching Configuration objects are provided. With a factory component, multiple component configurations can be created all using the Configuration objects matching the configuration PIDs.

A configuration change can cause a component configuration to become unsatisfied if any of the following occur:

  • A target property change results in a bound service of a static reference ceasing to be a target service.

  • A target property change results in unbound target services for a static reference with the greedy policy option.

  • A target property change or minimum cardinality property change results in a reference falling below the minimum cardinality.

  • The component description does not specify the modified attribute.

112.7.1.4 Configuration Change Actions

If a component configuration becomes unsatisfied:

  • SCR must deactivate the component configuration.

  • If the component configuration was not created from a factory component, SCR must attempt to satisfy the component configuration with the current configuration state.

If a component configuration remains satisfied:

  • If the component configuration has been activated, the modified method is called to provide the updated component properties. See Modification for more information.

  • If the component configuration is registered as a service, SCR must modify the service properties.

112.7.1.5 Coordinator Support

The Coordinator Service Specification defines a mechanism for multiple parties to collaborate on a common task without a priori knowledge of who will collaborate in that task. Like Configuration Admin Service Specification, SCR must participate in such scenarios to coordinate with provisioning or configuration tasks.

If configurations changes occur and an implicit coordination exists, SCR must delay taking action on the configuration changes until the coordination terminates, regardless of whether the coordination fails or terminates regularly.

112.8 Annotations

A number of CLASS retention annotations have been provided to allow tools to construct the component description XML from the Java class files. The Component Annotations are intended to be used during build time to generate the component description XML.

Component Property Types, which are user defined annotations, can be used to describe component properties in the component description XML and to access those component properties at runtime in a type safe manner.

112.8.1 Component Annotations

The Component Annotations provide a convenient way to create the component description XML during build time. Since annotations are placed in the source file and can use types, fields, and methods, they can significantly simplify the use of Declarative Services.

The Component Annotations are build time annotations because one of the key aspects of Declarative Services is its laziness. SCR can easily read the component description XML from the bundle, preprocess it, and cache the results between framework invocations. This way it is unnecessary to load a class from the bundle when the bundle is started and/or scan the classes for annotations. Component Annotations are not recognized by SCR at runtime.

The Component Annotations are not inherited, they can only be used on a given class, annotations on its super class hierarchy or interfaces are not taken into account.

The primary annotation is the Component annotation. It indicates that a class is a component. Its defaults create the easiest to use component:

  • Its name is the class name

  • It registers all of the class's directly implemented interfaces as services

  • The instance will be shared by all bundles

  • It is enabled

  • It is immediate if it has no services, otherwise it is delayed

  • It has an optional configuration policy

  • The configuration PID is the class name

For example, the following class registers a Speech service that can run on a Macintosh:

public interface Speech {
  void say(String what) throws Exception;
}

@Component
public class MacSpeech implements Speech {
    ScriptEngine engine = 
        new ScriptEngineManager().getEngineByName("AppleScript");
    
    public void say(String message) throws Exception {
        engine.eval("say \"" + message.replace('"','\'' + "\"");
    }
}

The previous example would be processed at build time into a component description similar to the following XML:

<scr:component name="com.example.MacSpeech"
  xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0">
  <implementation class="com.acme.impl.MacSpeech"/>
  <service>
    <provide interface="com.acme.service.speech.Speech"/>
  </service>
</scr:component>

It is possible to add activate and deactivate methods on the component with the Activate and Deactivate annotations. If the component wants to be updated for changes in the configuration properties then it can also indicate the modified method with the Modified annotation. For example:

@Activate
void open(Map<String,?> properties) { ... }

@Deactivate
void close() { ... }

@Modified
void modified(Map<String,?> properties) { ... }

The Activate annotation can also be used on a field or a constructor. When used on a field, the field will be set during activation of the component. When used on a constructor, the constructor will be used to construct the component instances.

@Activate
ComponentContext context;

@Activate
public MacSpeech(Map<String,?> properties) { ... }

If a component has dependencies on other services then they can be referenced with the Reference annotation that can be applied to a bind method, a field, or a constructor parameter. For a bind method, the defaults for the Reference annotation are:

  • The name of the method is used for the name of the reference.

  • 1:1 cardinality.

  • Static reluctant policy.

  • The requested service is the type of the first parameter of the bind method.

  • It will infer a default unset method and updated method based on the name of the bind method.

For example:

@Reference(cardinality=MULTIPLE, policy=DYNAMIC)
void setLogService( LogService log, Map<String,?> props) { ... }
void unsetLogService( LogService log ) {  ... }
void updatedLogService( Map<String,?> map ) { ...}

For a field, the defaults for the Reference annotation are:

  • The name of the field is used for the name of the reference.

  • 0..n cardinality if the field is a collection. 0..1 cardinality if the field is of type Optional. 1:1 cardinality otherwise.

  • Static reluctant policy if the field is not declared volatile. Dynamic reluctant policy if the field is declared volatile.

  • The requested service is the type of the field.

For example:

@Reference
volatile Collection<LogService> log;

For a constructor parameter, the defaults for the Reference annotation are:

  • The name of the parameter is used for the name of the reference if method parameter names are included in the class file. Otherwise, a name for the reference must be generated.

  • 0..n cardinality if the parameter is a collection. 0..1 cardinality if the parameter is of type Optional. 1:1 cardinality otherwise.

  • Static reluctant policy.

  • The requested service is the type of the parameter.

For example:

@Activate
public MacSpeech(@Reference Collection<LogService> log) { ... }

112.8.2 Component Property Types

Component properties can be defined and accessed through a user defined annotation type, called a component property type, containing the property names, property types and default values. A component property type allows properties to be defined and accessed in a type safe manner. Component property types can themselves be annotated with the ComponentPropertyType meta-annotation.

The following example shows the definition of a component property type called Config which defines three properties where the name of the property is the name of the method, the type of the property is the return type of the method and the default value for the property is the default value of the method.

@ComponentPropertyType
public @interface Config {
  boolean enabled() default true;
  String[] names() default {"a", "b"};
  String topic() default "default/topic";
}

Component property types can be used in two ways:

  • Component property types can be used to annotate the component implementation class, along side the Component annotation. The annotation usage can specify property values which can be different than the default values declared in the component property type.

    To be used in this way, the component property type must be annotated with the ComponentPropertyType meta-annotation so that, at build time, the annotation is recognized as a component property type.

  • Component property types can be used as parameter types in the component's constructor and life cycle methods, or as field types for activation fields. The component implementation can use objects of a component property type at runtime to access component property values in a type safe manner.

    To be used in this way, it is recommended the component property type be annotated with the ComponentPropertyType meta-annotation but it is not required.

Both ways define property names, types and values for the component.

The following example shows the component implementation annotated with the example Config component property type which specifies a property value for the component which is different than the default value. The example also shows the activate method taking the example Config component property type as a parameter type and the method implementation accesses component property values by invoking methods on the component property type object.

@Component
@Config(names="myapp")
public class MyComponent {
  @Activate
  void activate(Config config) {
    if (config.enabled()) {
      // do something
    }
    for (String name:config.names()) {
      // do something with each name
    }
  }
}

If a component implementation needs to access component properties which are not represented by a component property type, it can use a type of Map to receive the properties map in addition to component property types. For example:

@Component
public class MyComponent {
  @Activate
  void activate(Config config, Map<String, ?> allProperties) {
    if (config.enabled()) {
      // do something
    }
    if (allProperties.get("other.prop") != null) {
      // do something
    }
  }
}

Component property types must be defined as annotation types. This is done for several reasons. First, the limitations on annotation type definitions make them well suited for component property types. The methods must have no parameters and the return types supported are limited to a set which is well suited for component properties. Second, annotation types support default values which is useful for defining the default value of a component property. Finally, as annotations, they can be used to annotate component implementation classes.

At build time, the component property types must be processed to potentially generate property elements in the component description. See Ordering of Generated Component Properties.

At runtime, when SCR needs to provide a component instance an activation object whose type is a component property type, SCR must construct an instance of the component property type whose methods are backed by the values of the component properties for the component instance. This object can then be used to obtain the property values in a type safe manner.

112.8.2.1 Component Property Mapping

Each method of a configuration property type is mapped to a component property. The property name is derived from the method name. Certain common property name characters, such as full stop ('.' \u002E) and hyphen-minus ('-' \u002D) are not valid in Java identifiers. So the name of a method must be converted to its corresponding property name as follows:

  • A single dollar sign ('$' \u0024) is removed unless it is followed by:

    • A low line ('_' \u005F) and a dollar sign in which case the three consecutive characters ("$_$") are converted to a single hyphen-minus ('-' \u002D).

    • Another dollar sign in which case the two consecutive dollar signs ("$$") are converted to a single dollar sign.

  • A single low line ('_' \u005F) is converted into a full stop ('.' \u002E) unless is it followed by another low line in which case the two consecutive low lines ("__") are converted to a single low line.

  • All other characters are unchanged.

  • If the component property type declares a PREFIX_ field whose value is a compile-time constant String, then the property name is prefixed with the value of the PREFIX_ field.

Table 112.11 contains some name mapping examples.

Table 112.11 Component Property Name Mapping Examples

Component Property Type Method Name Component Property Name
myProperty143 myProperty143
$new new
my$$prop my$prop
dot_prop dot.prop
_secret .secret
another__prop another_prop
three___prop three_.prop
four_$__prop four._prop
five_$_prop five..prop
six$_$prop six-prop
seven$$_$prop seven$.prop

However, if the component property type is a single-element annotation, see 9.7.3 in [7] The Java Language Specification, Java SE 8 Edition, then the property name for the value method is derived from the name of the component property type rather than the name of the method.

In this case, the simple name of the component property type, that is, the name of the class without any package name or outer class name, if the component property type is an inner class, must be converted to the property name as follows:

  • When a lower case character is followed by an upper case character, a full stop ('.' \u002E) is inserted between them.

  • Each upper case character is converted to lower case.

  • All other characters are unchanged.

  • If the component property type declares a PREFIX_ field whose value is a compile-time constant String, then the property name is prefixed with the value of the PREFIX_ field.

Table 112.12 contains some mapping examples for the value method.

Table 112.12 Single-Element Annotation Mapping Examples for value Method

Component Property Type Name value Method Component Property Name
ServiceRanking service.ranking
Some_Name some_name
OSGiProperty osgi.property

If the component property type is a marker annotation, see 9.7.2 in [7] The Java Language Specification, Java SE 8 Edition, then the property name is derived from the name of the component property type, as is described above for single-element annotations, and the value of the property is Boolean.TRUE. Marker annotations can be used to annotate component implementation classes to set a component property to the value Boolean.TRUE. However, since marker annotations have no methods, they are of no use as parameter types in the component's constructor and life cycle methods, or as field types for activation fields.

The property type can be directly derived from the type of the method. All types supported for annotation elements can be used except for annotation types. Method types of an annotation type or array thereof are not supported. A tool processing the component property types must ignore such methods.

If the method type is Class or Class[], then the property type must be String or String[], respectively, whose values are fully qualified class names in the form returned by the Class.getName() method.

If the method type is an enumeration type or an array thereof, then the property type must be String or String[], respectively, whose values are the names of the enum constants in the form returned by the Enum.name() method.

112.8.2.2 Coercing Component Property Values

When a component property type is used as an activation object type, SCR must create an object that implements the component property type and maps the methods of the component property type to component properties. The name of the method is converted to the property name as described in Component Property Mapping. The property value may need to be coerced to the type of the method. In Table 112.13, the columns are source types, that is, the type of the component property value, and the rows are target types, that is, the method types. The property value is v; number is a primitive numerical type and Number is a wrapper numerical type. An invalid coercion is represented by throw. Such a coercion attempt must result in throwing a Component Exception when the component property type method is called. Any other coercion error, such as parsing a non-numerical string to a number or the inability to coerce a string into a Class or enum object, must be wrapped in a Component Exception and thrown when the component property type method is called.

Table 112.13 Coercion From Property Value to Method Type

target \ source String Boolean Character Number Collection/array
String v v. toString() v. toString() v. toString() If v has no elements, null; otherwise the first element of v is coerced.
boolean Boolean. parseBoolean( v ) v. booleanValue() v. charValue() != 0 v. doubleValue() != 0 If v has no elements, false; otherwise the first element of v is coerced.
char v. length() > 0 ? v. charAt(0) : 0 v. booleanValue() ? 1 : 0 v. charValue() (char) v. intValue() If v has no elements, 0; otherwise the first element of v is coerced.
number Number. parseNumber( v ) v. booleanValue() ? 1 : 0 (number) v. charValue() v. numberValue() If v has no elements, 0; otherwise the first element of v is coerced.
Class Bundle. loadClass( v ) throw throw throw If v has no elements, null; otherwise the first element of v is coerced.
EnumType EnumType. valueOf( v ) throw throw throw If v has no elements, null; otherwise the first element of v is coerced.
annotation type throw throw throw throw throw
array A single element array is created and v is coerced into the single element of the new array. An array the size of v is created and each element of v is coerced into the corresponding element of the new array.

Component properties whose names do not map to component property type methods are ignored. If there is no corresponding component property for a component property type method, the component property type method must:

  • Return 0 for numerical and char method types.

  • Return false for boolean method type.

  • Return null for String, Class, and enum.

  • Return an empty array for array method types.

  • Throw a ComponentException for annotation method types.

112.8.2.3 Standard Component Property Types

Component property types for standard component properties are specified in the org.osgi.service.component.propertytypes package.

The ServiceDescription component property type can be used to add the service.description service property to a component. The ServiceRanking component property type can be used to add the service.ranking service property to a component. The ServiceVendor component property type can be used to add the service.vendor service property to a component. For example, using these component property types as annotations:

@Component
@ServiceDescription(”My Acme Service implementation”)
@ServiceRanking(100)
@ServiceVendor("My Corp")
public class MyComponent implements AcmeService {}

will result in the following component properties:

<property name=”service.description” value=”My Acme Service implementation”/>
<property name=”service.ranking” type=”Integer” value=”100”/>
<property name=”service.vendor” value=”My Corp”/>

The ExportedService component property type can be used to specify service properties for remote services.

The SatisfyingConditionTarget component property type can be used to specify the target property for a reference to the satisfying condition of a component configuration. See Satisfying Condition.

112.8.3 Ordering of Generated Component Properties

The Component annotation contains two ways to define component properties via the property and properties elements. See Property and Properties Elements. If Component Annotations are used to describe the component, then any component property types used as the type of an activation object or used to annotate the component implementation class must also be processed since component property types can be used to define component property values as well. See Component Property Types. A tool processing the Component Annotations and the component property types must write the defined component properties into the generated component description in the following order.

  1. Properties defined through component property types used as the type of an activation object.

    If any of the referenced component property types have methods with defaults, then the generated component description must include a property element for each such method with the property name mapped from the method name, the property type mapped from the method type, and the property value set to the method's default value. See Component Property Mapping. The generated property elements must be added to the component description by processing the component property types used as the type of an activation object in the following order:

    1. The component property types used as parameters to the constructor.

    2. The component property types used as activation fields. The fields are processed in lexicographical order, using String.compareTo, of the field names.

    3. The component property types used as parameters to the activate method.

    4. The component property types used as parameters to the modified method.

    5. The component property types used as parameters to the deactivate method.

    If a method has more than one component property type parameter, the component property types are processed in the order of the method parameters.

    For component property type methods without a default value or with a default value of an empty array, a property element must not be generated.

  2. Properties defined through component property types annotating the component implementation class.

    The generated component description must include a property element for each such method with the property name mapped from the method name, the property type mapped from the method type, and the property value set to the method's value. See Component Property Mapping. The generated property elements must be added to the component description by processing the component property types annotating the component implementation class in the order that the annotations appear in the component implementation's class file. However, the order of the RuntimeVisibleAnnotations and RuntimeInvisibleAnnotations attributes in the class file is unspecified by [6] The Java Virtual Machine Specification, Java SE 8 Edition so care must be taken when using component property types of different RetentionPolicy that have method names in common.

    For component property type methods with a value of an empty array, a property element must not be generated.

  3. property element of the Component annotation.

  4. properties element of the Component annotation.

This means that the properties defined through component property types are declared first in the generated component description, followed by all properties defined through the property element of the Component annotation and finally the properties entries defined through the properties element of the Component annotation.

Since property values defined later in the component description override property values defined earlier in the component description, this means that property values defined in properties element of the Component annotation can override property values defined in property element of the Component annotation which can override values defined by values in the component property types.

112.9 Service Component Runtime

Service Component Runtime (SCR) is the actor that manages the components and their life cycle and allows introspection of the components.

112.9.1 Relationship to OSGi Framework

SCR must have access to the Bundle Context of any bundle that contains a component. SCR needs access to the Bundle Context for the following reasons:

  • To be able to register and get services on behalf of a bundle with components.

  • To interact with the Configuration Admin on behalf of a bundle with components.

  • To provide a component its Bundle Context when the Component Context getBundleContext method is called.

SCR should use the Bundle.getBundleContext() method to obtain the Bundle Context reference.

112.9.2 Starting and Stopping SCR

When SCR is implemented as a bundle, any component configurations activated by SCR must be deactivated when the SCR bundle is stopped. When the SCR bundle is started, it must process any components that are declared in bundles that are started. This includes bundles which are started and are awaiting lazy activation.

112.9.3 Logging Messages

When SCR must log a message to the Log Service, it must use a Logger named for the component implementation class and associated with the bundle declaring the component. To obtain the Logger object, SCR must call the LoggerFactory.getLogger(Bundle bundle, String name, Class loggerType) method passing the bundle declaring the component as the first argument and the fully qualified name of the component implementation class as the second argument. If SCR cannot know the component implementation class name, because the error is not associated with a component or the error occurred before the component description is processed, then SCR must use the bundle's Root Logger, that is, the Logger named ROOT.

112.9.4 Locating Component Methods and Fields

SCR will need to locate activate, deactivate, modified, bind, updated, and unbind methods as well as fields in a component instance. These members will be located, and called or modified, using reflection. The declared members of each class in the component implementation class's hierarchy are examined for a suitable member. If a suitable member is found in a class, and it is accessible to the component implementation class, then that member must be used. If suitable members are found in a class but none of the suitable members are accessible by the component implementation class, then the search for suitable members terminates with no suitable member having been located. If no suitable members are found in a class, the search continues in the superclass.

Only members that are accessible to the component implementation class will be used. If the member has the public or protected access modifier, then access is permitted. Otherwise, if the member has the private access modifier, then access is permitted only if the member is declared in the component implementation class. Otherwise, if the member has default access, also known as package private access, then access is permitted only if the member is declared in the component implementation class or if the member is declared in a superclass and all classes in the hierarchy from the component implementation class to the superclass, inclusive, are in the same package and loaded by the same class loader.

It is recommended that these members should not be declared with the public access modifier so that they do not appear as public members on the component instance when it is used as a service object. Having these members declared public allows any code to call or access the members with reflection, even if a Security Manager is installed. These members are generally intended to only be called or modified by SCR.

112.9.5 Bundle Activator Interaction

A bundle containing components may also declare a Bundle Activator. Such a bundle may also be marked for lazy activation. Since components are activated by SCR and Bundle Activators are called by the OSGi Framework, a bundle using both components and a Bundle Activator must take care. The Bundle Activator's start method must not rely upon SCR having activated any of the bundle's components. However, the components can rely upon the Bundle Activator's start method having been called. That is, there is a happens-before relationship between the Bundle Activator's start method being run and the components being activated.

112.9.6 Introspection

SCR provides an introspection API for examining the runtime state of the components in bundles processed by SCR. SCR must register a ServiceComponentRuntime service upon startup. The Service Component Runtime service provides methods to inspect the component descriptions and component configurations as well as inspect and modify the enabled state of components. The service uses Data Transfer Objects (DTO) as parameters and return values. The rules for Data Transfer Objects are specified in OSGi Core Release 8.

The Service Component Runtime service provides the following methods.

  • getComponentDescriptionDTOs(Bundle...) - For each specified bundle, if the bundle is active and processed by SCR, the returned collection will contain a ComponentDescriptionDTO for each valid component description in the bundle.

  • getComponentDescriptionDTO(Bundle,String) - If the specified bundle is active and processed by SCR, and the specified bundle contains a valid component description with the specified name, the method will return a ComponentDescriptionDTO for the component description.

  • getComponentConfigurationDTOs(ComponentDescriptionDTO) - If the specified ComponentDescriptionDTO represents a valid component description from an active bundle processed by SCR, the returned collection will contain a ComponentConfigurationDTO for each component configuration of the component.

  • isComponentEnabled(ComponentDescriptionDTO) - Returns true if the specified Component Description DTO represents a valid component description from an active bundle processed by SCR, and the component is enabled. Otherwise, the method returns false.

  • enableComponent(ComponentDescriptionDTO) - If the specified Component Description DTO represents a valid component description from an active bundle processed by SCR, the component is enabled. This method must return after changing the enabled state of the specified component. Any actions that result from this, such as activating or deactivating a component configuration, must occur asynchronously to this method call. The method returns a Promise that will be resolved when the actions that result from changing the enabled state of the specified component have completed.

  • disableComponent(ComponentDescriptionDTO) - If the specified Component Description DTO represents a valid component description from an active bundle processed by SCR, the component is disabled. This method must return after changing the enabled state of the specified component. Any actions that result from this, such as activating or deactivating a component configuration, must occur asynchronously to this method call. The method returns a Promise that will be resolved when the actions that result from changing the enabled state of the specified component have completed.

The runtime state of the components can change at any time. So any information returned by these methods only provides a snapshot of the state at the time of the method call.

There are a number of DTOs available via the Service Component Runtime service.

Figure 112.6 Service Component Runtime DTOs

Service Component Runtime DTOs

The two main DTOs are ComponentDescriptionDTO, which represents a component description, and ComponentConfigurationDTO, which represents a component configuration. The Component Description DTO contains an array of ReferenceDTO objects which represent each declared reference in the component description. The Component Configuration DTO contains an array of SatisfiedReferenceDTO objects and an array of UnsatisfiedReferenceDTO objects. A Satisfied Reference DTO represents a satisfied reference of the component configuration and an Unsatisfied Reference DTO represents an unsatisfied reference of the component configuration. The Component Configuration DTO for a satisfied component configuration must contain no Unsatisfied Reference DTOs. The Component Configuration DTO for an unsatisfied component configuration may contain some Satisfied Reference DTOs and some Unsatisfied Reference DTOs. This information can be used to diagnose why the component configuration is not satisfied.

SCR must register the ServiceComponentRuntime service with the service.changecount service property. See org.osgi.framework.Constants.SERVICE_CHANGECOUNT in OSGi Core Release 8. Whenever the Service Component Runtime DTOs available from the ServiceComponentRuntime service change, SCR modify the service.changecount service property with an updated change count value. This allows interested parties to be notified of changes to the DTOs by observing Service Events of type MODIFIED for the ServiceComponentRuntime service.

112.9.7 Capabilities

SCR must provide the following capabilities.

  • A capability in the osgi.extender namespace declaring an extender with the name COMPONENT_CAPABILITY_NAME. This capability must also declare a uses constraint for the org.osgi.service.component package. For example:

    Provide-Capability: osgi.extender;
        osgi.extender="osgi.component";
        version:Version="1.5";
        uses:="org.osgi.service.component"

    This capability must follow the rules defined for the osgi.extender Namespace.

    A bundle that contains service components should require the osgi.extender capability from SCR. This requirement will wire the bundle to the SCR implementation and ensure that SCR is using the same org.osgi.service.component package as the bundle if the bundle uses that package.

    Require-Capability: osgi.extender;
      filter:="(&(osgi.extender=osgi.component)(version>=1.5)(!(version>=2.0)))"

    The RequireServiceComponentRuntime annotation can be used to require this capability. The Component annotation is meta-annotated with this annotation.

    SCR must only process a bundle's service components if one of the following is true:

    • The bundle's wiring has a required wire for at least one osgi.extender capability with the name osgi.component and the first of these required wires is wired to SCR.

    • The bundle's wiring has no required wire for an osgi.extender capability with the name osgi.component.

    Otherwise, SCR must not process the bundle's service components.

  • A capability in the osgi.service namespace representing the ServiceComponentRuntime service. This capability must also declare a uses constraint for the org.osgi.service.component.runtime package. For example:

    Provide-Capability: osgi.service;
        objectClass:List<String>=
          "org.osgi.service.component.runtime.ServiceComponentRuntime";
        uses:="org.osgi.service.component.runtime"

    This capability must follow the rules defined for the osgi.service Namespace.

112.9.8 Locating the True Condition Service

SCR must locate the True Condition service. This can be done using the Bundle Context of SCR itself. However, if SCR is unable to locate the True Condition service using the Bundle Context of SCR itself, it may retry using the Bundle Context of the system bundle. This retry to locate the True Condition service can succeed when a service hook implementation is in use that has not been updated to support the Condition Service Specification by providing visibility of the True Condition service to all bundles.

If SCR is unable to locate the True Condition service, which can occur if SCR is running on an older OSGi Framework which does not support the Condition Service Specification and register the True Condition service, then SCR must not augment component descriptions to add the implicit reference for a satisfying condition. See Satisfying Condition.

SCR may use the already located True Condition service to satisfy any component configuration's reference to the True Condition service.

112.10 Security

When Java permissions are enabled, SCR must perform the following security procedures.

112.10.1 Service Permissions

Declarative services are built upon the existing OSGi service infrastructure. This means that Service Permission applies regarding the ability to publish, find or bind services.

If a component specifies a service, then component configurations for the component cannot be satisfied unless the component's bundle has ServicePermission[<provides>, REGISTER] for each provided interface specified for the service.

If a component's reference does not specify optional cardinality, the reference cannot be satisfied unless the component's bundle has ServicePermission[<interface>, GET] for the specified interface in the reference. If the reference specifies optional cardinality but the component's bundle does not have ServicePermission[<interface>, GET] for the specified interface in the reference, no service must be bound for this reference.

If a component is a factory component, then the above Service Permission checks still apply. But the component's bundle is not required to have ServicePermission[ComponentFactory, REGISTER] as the Component Factory service is registered by SCR.

SCR must have ServicePermission[ServiceComponentRuntime, REGISTER] permission to register the ServiceComponentRuntime service. Administrative bundles wishing to use the ServiceComponentRuntime service must have ServicePermission[ServiceComponentRuntime, GET] permission. In general, this permission should only be granted to administrative bundles to limit access to the potentially intrusive methods provided by this service.

112.10.2 Required Admin Permission

SCR requires AdminPermission[*,CONTEXT] because it needs access to the bundle's Bundle Context object with the Bundle.getBundleContext() method.

112.10.3 Using hasPermission

SCR does all publishing, finding and binding of services on behalf of the component using the Bundle Context of the component's bundle. This means that normal stack-based permission checks will check SCR and not the component's bundle. Since SCR is registering and getting services on behalf of a component's bundle, SCR must call the Bundle.hasPermission method to validate that a component's bundle has the necessary permission to register or get a service.

112.10.4 Configuration Multi-Locations and Regions

SCR must ensure a bundle has the proper ConfigurationPermission for a Configuration used by its components when the Configuration has a multi-location. See Using Multi-Locations for more information on multi-locations and Regions for more information on regions. If a bundle does not have the necessary permission for a multi-location Configuration, then SCR must act as if the Configuration does not exist for the bundle.

112.11 Component Description Schema

This XML Schema defines the component description grammar.

<schema xmlns="http://www.w3.org/2001/XMLSchema"
    xmlns:scr="http://www.osgi.org/xmlns/scr/v1.5.0"
    targetNamespace="http://www.osgi.org/xmlns/scr/v1.5.0"
    elementFormDefault="unqualified"
    attributeFormDefault="unqualified"
    version="1.5.0">

    <annotation>
        <documentation xml:lang="en">
            This is the XML Schema for component descriptions used by
            the Service Component Runtime (SCR). Component description
            documents may be embedded in other XML documents. SCR will
            process all XML documents listed in the Service-Component
            manifest header of a bundle. XML documents containing
            component descriptions may contain a single, root component
            element or one or more component elements embedded in a
            larger document. Use of the namespace for component 
            descriptions is mandatory. The attributes and subelements 
            of a component element are always unqualified.
        </documentation>
    </annotation>
    <element name="component" type="scr:Tcomponent" />
    <complexType name="Tcomponent">
        <sequence>
            <annotation>
                <documentation xml:lang="en">
                    Implementations of SCR must not require component
                    descriptions to specify the subelements of the component
                    element in the order as required by the schema. SCR
                    implementations must allow other orderings since
                    arbitrary orderings do not affect the meaning of the
                    component description. Only the relative ordering of
                    property and properties element have meaning.
                </documentation>
            </annotation>
            <choice minOccurs="0" maxOccurs="unbounded">
                <element name="property" type="scr:Tproperty" />
                <element name="properties" type="scr:Tproperties" />
            </choice>
            <choice minOccurs="0" maxOccurs="unbounded">
                <element name="factory-property" type="scr:Tproperty" />
                <element name="factory-properties" type="scr:Tproperties" />
            </choice>
            <element name="service" type="scr:Tservice" minOccurs="0"
                maxOccurs="1" />
            <element name="reference" type="scr:Treference"
                minOccurs="0" maxOccurs="unbounded" />
            <element name="implementation" type="scr:Timplementation" />
            <any namespace="##any" processContents="lax" minOccurs="0"
                maxOccurs="unbounded" />
        </sequence>
        <attribute name="enabled" type="boolean" default="true"
            use="optional" />
        <attribute name="name" type="token" use="optional">
            <annotation>
                <documentation xml:lang="en">
                    The default value of this attribute is the value of
                    the class attribute of the nested implementation
                    element. If multiple component elements use the same 
                    value for the class attribute of their nested 
                    implementation element, then using the default value 
                    for this attribute will result in duplicate names. 
                    In this case, this attribute must be specified with 
                    a unique value.
                </documentation>
            </annotation>
        </attribute>
        <attribute name="factory" type="string" use="optional" />
        <attribute name="immediate" type="boolean" use="optional" />
        <attribute name="configuration-policy"
            type="scr:Tconfiguration-policy" default="optional" use="optional" />
        <attribute name="activate" type="token" use="optional"
            default="activate" />
        <attribute name="deactivate" type="token" use="optional"
            default="deactivate" />
        <attribute name="modified" type="token" use="optional" />
        <attribute name="configuration-pid" use="optional">
            <annotation>
                <documentation xml:lang="en">
                    The default value of this attribute is the value of
                    the name attribute of this element.
                </documentation>
            </annotation>
            <simpleType>
                <restriction>
                    <simpleType>
                        <list itemType="token" />
                    </simpleType>
                    <minLength value="1" />
                </restriction>
            </simpleType>
        </attribute>
        <attribute name="activation-fields" use="optional">
            <simpleType>
                <restriction>
                    <simpleType>
                        <list itemType="token" />
                    </simpleType>
                    <minLength value="1" />
                </restriction>
            </simpleType>
        </attribute>
        <attribute name="init" type="unsignedByte" default="0"
            use="optional" />
        <anyAttribute processContents="lax" />
    </complexType>
    <complexType name="Timplementation">
        <sequence>
            <any namespace="##any" processContents="lax" minOccurs="0"
                maxOccurs="unbounded" />
        </sequence>
        <attribute name="class" type="token" use="required" />
        <anyAttribute processContents="lax" />
    </complexType>
    <complexType name="Tproperty">
        <simpleContent>
            <extension base="string">
                <attribute name="name" type="string" use="required" />
                <attribute name="value" type="string" use="optional" />
                <attribute name="type" type="scr:Tproperty_type"
                    default="String" use="optional" />
                <anyAttribute processContents="lax" />
            </extension>
        </simpleContent>
    </complexType>
    <complexType name="Tproperties">
        <sequence>
            <any namespace="##any" processContents="lax" minOccurs="0"
                maxOccurs="unbounded" />
        </sequence>
        <attribute name="entry" type="string" use="required" />
        <anyAttribute processContents="lax" />
    </complexType>
    <complexType name="Tservice">
        <sequence>
            <element name="provide" type="scr:Tprovide" minOccurs="1"
                maxOccurs="unbounded" />
            <!-- It is non-deterministic, per W3C XML Schema 1.0: 
            http://www.w3.org/TR/xmlschema-1/#cos-nonambig
            to use name space="##any" below. -->
            <any namespace="##other" processContents="lax" minOccurs="0"
                maxOccurs="unbounded" />
        </sequence>
        <attribute name="scope" type="scr:Tservice_scope" default="singleton"
            use="optional" />
        <anyAttribute processContents="lax" />
    </complexType>
    <complexType name="Tprovide">
        <sequence>
            <any namespace="##any" processContents="lax" minOccurs="0"
                maxOccurs="unbounded" />
        </sequence>
        <attribute name="interface" type="token" use="required" />
        <anyAttribute processContents="lax" />
    </complexType>
    <complexType name="Treference">
        <sequence>
            <any namespace="##any" processContents="lax" minOccurs="0"
                maxOccurs="unbounded" />
        </sequence>
        <attribute name="name" type="token" use="optional">
            <annotation>
                <documentation xml:lang="en">
                    The default value of this attribute is the value of
                    the interface attribute of this element. If multiple 
                    instances of this element within a component element 
                    use the same value for the interface attribute, then 
                    using the default value for this attribute will result 
                    in duplicate names. In this case, this attribute 
                    must be specified with a unique value.
                </documentation>
            </annotation>
        </attribute>
        <attribute name="interface" type="token" use="required" />
        <attribute name="cardinality" type="scr:Tcardinality"
            default="1..1" use="optional" />
        <attribute name="policy" type="scr:Tpolicy" default="static"
            use="optional" />
        <attribute name="policy-option" type="scr:Tpolicy-option" 
            default="reluctant" use="optional" />
        <attribute name="target" type="string" use="optional" />
        <attribute name="bind" type="token" use="optional" />
        <attribute name="unbind" type="token" use="optional" />
        <attribute name="updated" type="token" use="optional" />
        <attribute name="scope" type="scr:Treference_scope" default="bundle"
            use="optional" />
        <attribute name="field" type="token" use="optional" />
        <attribute name="field-option" type="scr:Tfield-option" default="replace"
            use="optional" />
        <attribute name="field-collection-type" type="scr:Tfield-collection-type"
            default="service" use="optional" />
        <attribute name="parameter" type="unsignedByte" use="optional" />
        <anyAttribute processContents="lax" />
    </complexType>
    <simpleType name="Tproperty_type">
        <restriction base="string">
            <enumeration value="String" />
            <enumeration value="Long" />
            <enumeration value="Double" />
            <enumeration value="Float" />
            <enumeration value="Integer" />
            <enumeration value="Byte" />
            <enumeration value="Character" />
            <enumeration value="Boolean" />
            <enumeration value="Short" />
        </restriction>
    </simpleType>
    <simpleType name="Tcardinality">
        <restriction base="string">
            <enumeration value="0..1" />
            <enumeration value="0..n" />
            <enumeration value="1..1" />
            <enumeration value="1..n" />
        </restriction>
    </simpleType>
    <simpleType name="Tpolicy">
        <restriction base="string">
            <enumeration value="static" />
            <enumeration value="dynamic" />
        </restriction>
    </simpleType>
    <simpleType name="Tpolicy-option">
        <restriction base="string">
            <enumeration value="reluctant" />
            <enumeration value="greedy" />
        </restriction>
    </simpleType>
    <simpleType name="Tconfiguration-policy">
        <restriction base="string">
            <enumeration value="optional" />
            <enumeration value="require" />
            <enumeration value="ignore" />
        </restriction>
    </simpleType>
    <simpleType name="Tservice_scope">
        <restriction base="string">
            <enumeration value="singleton" />
            <enumeration value="bundle" />
            <enumeration value="prototype" />
        </restriction>
    </simpleType>
    <simpleType name="Treference_scope">
        <restriction base="string">
            <enumeration value="bundle" />
            <enumeration value="prototype" />
            <enumeration value="prototype_required" />
        </restriction>
    </simpleType>
    <simpleType name="Tfield-option">
        <restriction base="string">
            <enumeration value="replace" />
            <enumeration value="update" />
        </restriction>
    </simpleType>
    <simpleType name="Tfield-collection-type">
        <restriction base="string">
            <enumeration value="service" />
            <enumeration value="properties" />
            <enumeration value="reference" />
            <enumeration value="serviceobjects" />
            <enumeration value="tuple" />
        </restriction>
    </simpleType>
    <attribute name="must-understand" type="boolean">
        <annotation>
            <documentation xml:lang="en">
                This attribute should be used by extensions to documents
                to require that the document consumer understand the
                extension. This attribute must be qualified when used.
            </documentation>
        </annotation>
    </attribute>
</schema>

SCR must not require component descriptions to specify the elements in the order required by the schema. SCR must allow other orderings since arbitrary orderings of these elements do not affect the meaning of the component description. Only the relative ordering of property, properties and reference elements have meaning for overriding previously set property values.

The schema is also available in digital form from [5] OSGi XML Schemas.

112.12 org.osgi.service.component

Version 1.5

Service Component Package Version 1.5.

Bundles wishing to use this package must list the package in the Import-Package header of the bundle's manifest. This package has two types of users: the consumers that use the API in this package and the providers that implement the API in this package.

Example import for consumers using the API in this package:

Import-Package: org.osgi.service.component; version="[1.5,2.0)"

Example import for providers implementing the API in this package:

Import-Package: org.osgi.service.component; version="[1.5,1.6)"

112.12.1 Summary

  • AnyService - A marker type whose name is used in the interface attribute of a reference element in a component description to indicate that the type of the service for a reference is not specified and can thus be any service type.

  • ComponentConstants - Defines standard names for Service Component constants.

  • ComponentContext - A Component Context object is used by a component instance to interact with its execution context including locating services by reference name.

  • ComponentException - Unchecked exception which may be thrown by Service Component Runtime.

  • ComponentFactory - When a component is declared with the factory attribute on its component element, Service Component Runtime will register a Component Factory service to allow new component configurations to be created and activated rather than automatically creating and activating component configuration as necessary.

  • ComponentInstance - A ComponentInstance encapsulates a component instance of an activated component configuration.

  • ComponentServiceObjects - Allows multiple service objects for a service to be obtained.

112.12.2 public final class AnyService

A marker type whose name is used in the interface attribute of a reference element in a component description to indicate that the type of the service for a reference is not specified and can thus be any service type.

When specifying this marker type in the interface attribute of a reference element in a component description:

  • The service type of the reference member or parameter must be java.lang.Object so that any service object can be provided.

  • The target attribute of the reference element must be specified to constrain the target services.

For example:

 @Reference(service = AnyService.class, target = "(osgi.jakartars.extension=true)")
 List<Object> extensions;

1.5

112.12.3 public interface ComponentConstants

Defines standard names for Service Component constants.

Consumers of this API must not implement this type

112.12.3.1 public static final String COMPONENT_CAPABILITY_NAME = "osgi.component"

Capability name for Service Component Runtime.

Used in Provide-Capability and Require-Capability manifest headers with the osgi.extender namespace. For example:

 Require-Capability: osgi.extender;
  filter:="(&(osgi.extender=osgi.component)(version>=1.5)(!(version>=2.0)))"

1.3

112.12.3.2 public static final String COMPONENT_FACTORY = "component.factory"

A service registration property for a Component Factory that contains the value of the factory attribute. The value of this property must be of type String.

112.12.3.3 public static final String COMPONENT_ID = "component.id"

A component property that contains the generated id for a component configuration. The value of this property must be of type Long.

The value of this property is assigned by Service Component Runtime when a component configuration is created. Service Component Runtime assigns a unique value that is larger than all previously assigned values since Service Component Runtime was started. These values are NOT persistent across restarts of Service Component Runtime.

112.12.3.4 public static final String COMPONENT_NAME = "component.name"

A component property for a component configuration that contains the name of the component as specified in the name attribute of the component element. The value of this property must be of type String.

112.12.3.5 public static final String COMPONENT_SPECIFICATION_VERSION = "1.5"

Compile time constant for the Specification Version of Declarative Services.

Used in Version and Requirement annotations. The value of this compile time constant will change when the specification version of Declarative Services is updated.

1.4

112.12.3.6 public static final int DEACTIVATION_REASON_BUNDLE_STOPPED = 6

The component configuration was deactivated because the bundle was stopped.

1.1

112.12.3.7 public static final int DEACTIVATION_REASON_CONFIGURATION_DELETED = 4

The component configuration was deactivated because its configuration was deleted.

1.1

112.12.3.8 public static final int DEACTIVATION_REASON_CONFIGURATION_MODIFIED = 3

The component configuration was deactivated because its configuration was changed.

1.1

112.12.3.9 public static final int DEACTIVATION_REASON_DISABLED = 1

The component configuration was deactivated because the component was disabled.

1.1

112.12.3.10 public static final int DEACTIVATION_REASON_DISPOSED = 5

The component configuration was deactivated because the component was disposed.

1.1

112.12.3.11 public static final int DEACTIVATION_REASON_REFERENCE = 2

The component configuration was deactivated because a reference became unsatisfied.

1.1

112.12.3.12 public static final int DEACTIVATION_REASON_UNSPECIFIED = 0

The reason the component configuration was deactivated is unspecified.

1.1

112.12.3.13 public static final String REFERENCE_NAME_SATISFYING_CONDITION = "osgi.ds.satisfying.condition"

Reference name for a component's satisfying condition.

1.5

112.12.3.14 public static final String REFERENCE_TARGET_SUFFIX = ".target"

The suffix for the target property of a reference. These properties contain the filter to select the target services for a reference. The value of a target property must be of type String.

112.12.3.15 public static final String SERVICE_COMPONENT = "Service-Component"

Manifest header specifying the XML documents within a bundle that contain the bundle's Service Component descriptions.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.

112.12.4 public interface ComponentContext

A Component Context object is used by a component instance to interact with its execution context including locating services by reference name. Each component instance has a unique Component Context.

A component instance may obtain its Component Context object through its activate, modified, and deactivate methods.

Thread-safe

Consumers of this API must not implement this type

112.12.4.1 public void disableComponent(String name)

The name of a component.

Disables the specified component name. The specified component name must be in the same bundle as this component.

This method must return after changing the enabled state of the specified component name. Any actions that result from this, such as activating or deactivating a component configuration, must occur asynchronously to this method call.

112.12.4.2 public void enableComponent(String name)

The name of a component or null to indicate all components in the bundle.

Enables the specified component name. The specified component name must be in the same bundle as this component.

This method must return after changing the enabled state of the specified component name. Any actions that result from this, such as activating or deactivating a component configuration, must occur asynchronously to this method call.

112.12.4.3 public BundleContext getBundleContext()

Returns the BundleContext of the bundle which declares this component.

The BundleContext of the bundle declares this component.

112.12.4.4 public ComponentInstance<S> getComponentInstance()

<S>

Returns the Component Instance object for the component instance associated with this Component Context.

The Component Instance object for the component instance.

112.12.4.5 public Dictionary<String, Object> getProperties()

Returns the component properties for this Component Context.

The properties for this Component Context. The Dictionary is read only and cannot be modified.

112.12.4.6 public ServiceReference<?> getServiceReference()

If the component instance is registered as a service using the service element, then this method returns the service reference of the service provided by this component instance.

This method will return null if the component instance is not registered as a service.

The ServiceReference object for the component instance or null if the component instance is not registered as a service.

112.12.4.7 public Bundle getUsingBundle()

If the component instance is registered as a service using the servicescope="bundle" or servicescope="prototype" attribute, then this method returns the bundle using the service provided by the component instance.

This method will return null if:

  • The component instance is not a service, then no bundle can be using it as a service.

  • The component instance is a service but did not specify the servicescope="bundle" or servicescope="prototype" attribute, then all bundles using the service provided by the component instance will share the same component instance.

  • The service provided by the component instance is not currently being used by any bundle.

The bundle using the component instance as a service or null.

112.12.4.8 public S locateService(String name)

<S>

The name of a reference as specified in a reference element in this component's description.

Returns the service object for the specified reference name.

If the cardinality of the reference is 0..n or 1..n and multiple services are bound to the reference, the service whose ServiceReference is first in the ranking order is returned. See ServiceReference.compareTo(Object).

A service object for the referenced service or null if the reference cardinality is 0..1 or 0..n and no bound service is available.

ComponentException– If Service Component Runtime catches an exception while activating the bound service.

112.12.4.9 public S locateService(String name, ServiceReference<S> reference)

<S>

Type of Service.

The name of a reference as specified in a reference element in this component's description.

The ServiceReference to a bound service. This must be a ServiceReference provided to the component via the bind or unbind method for the specified reference name.

Returns the service object for the specified reference name and ServiceReference.

A service object for the referenced service or null if the specified ServiceReference is not a bound service for the specified reference name.

ComponentException– If Service Component Runtime catches an exception while activating the bound service.

112.12.4.10 public Object[] locateServices(String name)

The name of a reference as specified in a reference element in this component's description.

Returns the service objects for the specified reference name.

An array of service objects for the referenced service or null if the reference cardinality is 0..1 or 0..n and no bound service is available. If the reference cardinality is 0..1 or 1..1 and a bound service is available, the array will have exactly one element. There is no guarantee that the service objects in the array will be in any specific order.

ComponentException– If Service Component Runtime catches an exception while activating a bound service.

112.12.5 public class ComponentException
extends RuntimeException

Unchecked exception which may be thrown by Service Component Runtime.

112.12.5.1 public ComponentException(String message, Throwable cause)

The message for the exception.

The cause of the exception. May be null.

Construct a new ComponentException with the specified message and cause.

112.12.5.2 public ComponentException(String message)

The message for the exception.

Construct a new ComponentException with the specified message.

112.12.5.3 public ComponentException(Throwable cause)

The cause of the exception. May be null.

Construct a new ComponentException with the specified cause.

112.12.5.4 public Throwable getCause()

Returns the cause of this exception or null if no cause was set.

The cause of this exception or null if no cause was set.

112.12.5.5 public Throwable initCause(Throwable cause)

The cause of this exception.

Initializes the cause of this exception to the specified value.

This exception.

IllegalArgumentException– If the specified cause is this exception.

IllegalStateException– If the cause of this exception has already been set.

112.12.6 public interface ComponentFactory<S>

Type of Service

When a component is declared with the factory attribute on its component element, Service Component Runtime will register a Component Factory service to allow new component configurations to be created and activated rather than automatically creating and activating component configuration as necessary.

Thread-safe

Consumers of this API must not implement this type

112.12.6.1 public ComponentInstance<S> newInstance(Dictionary<String, ?> properties)

Additional properties for the component configuration or null if there are no additional properties.

Create and activate a new component configuration. Additional properties may be provided for the component configuration.

A ComponentInstance object encapsulating the component instance of the component configuration. The component configuration has been activated and, if the component specifies a service element, the component instance has been registered as a service.

ComponentException– If Service Component Runtime is unable to activate the component configuration.

112.12.7 public interface ComponentInstance<S>

Type of Service

A ComponentInstance encapsulates a component instance of an activated component configuration. ComponentInstances are created whenever a component configuration is activated.

ComponentInstances are never reused. A new ComponentInstance object will be created when the component configuration is activated again.

Thread-safe

Consumers of this API must not implement this type

112.12.7.1 public void dispose()

Dispose of the component configuration for this component instance. The component configuration will be deactivated. If the component configuration has already been deactivated, this method does nothing.

112.12.7.2 public S getInstance()

Returns the component instance of the activated component configuration.

The component instance or null if the component configuration has been deactivated.

112.12.8 public interface ComponentServiceObjects<S>

Type of Service

Allows multiple service objects for a service to be obtained.

A component instance can receive a ComponentServiceObjects object via a reference that is typed ComponentServiceObjects.

For services with prototype scope, multiple service objects for the service can be obtained. For services with singleton or bundle scope, only one, use-counted service object is available.

Any unreleased service objects obtained from this ComponentServiceObjects object are automatically released by Service Component Runtime when the service becomes unbound.

ServiceObjects

1.3

Thread-safe

Consumers of this API must not implement this type

112.12.8.1 public S getService()

Returns a service object for the associated service.

This method will always return null when the associated service has been become unbound.

A service object for the associated service or null if the service is unbound, the customized service object returned by a ServiceFactory does not implement the classes under which it was registered or the ServiceFactory threw an exception.

IllegalStateException– If the component instance that received this ComponentServiceObjects object has been deactivated.

ungetService(Object)

112.12.8.2 public ServiceReference<S> getServiceReference()

Returns the ServiceReference for the service associated with this ComponentServiceObjects object.

The ServiceReference for the service associated with this ComponentServiceObjects object.

112.12.8.3 public void ungetService(S service)

A service object previously provided by this ComponentServiceObjects object.

Releases a service object for the associated service.

The specified service object must no longer be used and all references to it should be destroyed after calling this method.

IllegalStateException– If the component instance that received this ComponentServiceObjects object has been deactivated.

IllegalArgumentException– If the specified service object was not provided by this ComponentServiceObjects object.

getService()

112.13 org.osgi.service.component.annotations

Version 1.5

Service Component Annotations Package Version 1.5.

This package is not used at runtime. Annotated classes are processed by tools to generate Component Descriptions which are used at runtime.

112.13.1 Summary

112.13.2 @Activate

Identify the annotated member as part of the activation of a Service Component.

When this annotation is applied to a:

  • Method - The method is the activate method of the Component.

  • Constructor - The constructor will be used to construct the Component and can be called with activation objects and bound services as parameters.

  • Field - The field will contain an activation object of the Component. The field must be set after the constructor is called and before calling any other method on the fully constructed component instance. That is, there is a happens-before relationship between the field being set and calling any method on the fully constructed component instance such as the activate method.

This annotation is not processed at runtime by Service Component Runtime. It must be processed by tools and used to add a Component Description to the bundle.

The init, activate, and activation-fields attributes of the component element of a Component Description.

1.1

CLASS

METHOD, FIELD, CONSTRUCTOR

112.13.3 enum CollectionType

Collection types for the Reference annotation.

1.4

112.13.3.1 SERVICE

The service collection type is used to indicate the collection holds the bound service objects.

This is the default collection type.

112.13.3.2 REFERENCE

The reference collection type is used to indicate the collection holds Service References for the bound services.

112.13.3.3 SERVICEOBJECTS

The serviceobjects collection type is used to indicate the collection holds Component Service Objects for the bound services.

112.13.3.4 PROPERTIES

The properties collection type is used to indicate the collection holds unmodifiable Maps containing the service properties of the bound services.

The Maps must implement Comparable with the compareTo method comparing service property maps using an ordering which is the same as the natural ordering of ServiceReferences as specified in ServiceReference.compareTo.

112.13.3.5 TUPLE

The tuple collection type is used to indicate the collection holds unmodifiable Map.Entries whose key is an unmodifiable Map containing the service properties of the bound service, as specified in PROPERTIES, and whose value is the bound service object.

The Map.Entries must implement Comparable with the compareTo method comparing service property maps using an ordering which is the same as the natural ordering of ServiceReferences as specified in ServiceReference.compareTo.

112.13.3.6 public String toString()

112.13.3.7 public static CollectionType valueOf(String name)

112.13.3.8 public static CollectionType[] values()

112.13.4 @Component

Identify the annotated class as a Service Component.

The annotated class is the implementation class of the Component.

This annotation is not processed at runtime by Service Component Runtime. It must be processed by tools and used to add a Component Description to the bundle.

The component element of a Component Description.

CLASS

TYPE

112.13.4.1 String name default ""

The name of this Component.

If not specified, the name of this Component is the fully qualified type name of the class being annotated.

The name attribute of the component element of a Component Description.

112.13.4.2 Class<?>[] service default {}

The types under which to register this Component as a service.

If no service should be registered, the empty value {} must be specified.

If not specified, the service types for this Component are all the directly implemented interfaces of the class being annotated.

The service element of a Component Description.

112.13.4.3 String factory default ""

The factory identifier of this Component. Specifying a factory identifier makes this Component a Factory Component.

If not specified, the default is that this Component is not a Factory Component.

The factory attribute of the component element of a Component Description.

112.13.4.4 boolean servicefactory default false

Declares whether this Component uses the OSGi ServiceFactory concept and each bundle using this Component's service will receive a different component instance.

This element is ignored when the scope() element does not have the default value. If true, this Component uses bundle service scope. If false or not specified, this Component uses singleton service scope. If the factory() element is specified or the immediate() element is specified with true, this element can only be specified with false.

The scope attribute of the service element of a Component Description.

Since 1.3. Replaced by scope().

112.13.4.5 boolean enabled default true

Declares whether this Component is enabled when the bundle declaring it is started.

If true or not specified, this Component is enabled. If false, this Component is disabled.

The enabled attribute of the component element of a Component Description.

112.13.4.6 boolean immediate default false

Declares whether this Component must be immediately activated upon becoming satisfied or whether activation should be delayed.

If true, this Component must be immediately activated upon becoming satisfied. If false, activation of this Component is delayed. If this property is specified, its value must be false if the factory() property is also specified or must be true if the service() property is specified with an empty value.

If not specified, the default is false if the factory() property is specified or the service() property is not specified or specified with a non-empty value and true otherwise.

The immediate attribute of the component element of a Component Description.

112.13.4.7 String[] property default {}

Properties for this Component.

Each property string is specified as "name=value". The type of the property value can be specified in the name as name:type=value. The type must be one of the property types supported by the type attribute of the property element of a Component Description.

To specify a property with multiple values, use multiple name, value pairs. For example, {"foo=bar", "foo=baz"}.

The property element of a Component Description.

112.13.4.8 String[] properties default {}

Property entries for this Component.

Specifies the name of an entry in the bundle whose contents conform to a standard Java Properties File. The entry is read and processed to obtain the properties and their values.

The properties element of a Component Description.

112.13.4.9 String xmlns default ""

The XML name space of the Component Description for this Component.

If not specified, the XML name space of the Component Description for this Component should be the lowest Declarative Services XML name space which supports all the specification features used by this Component.

The XML name space specified for a Component Description.

112.13.4.10 ConfigurationPolicy configurationPolicy default OPTIONAL

The configuration policy of this Component.

Controls whether component configurations must be satisfied depending on the presence of a corresponding Configuration object in the OSGi Configuration Admin service. A corresponding configuration is a Configuration object where the PID equals the name of the component.

If not specified, the configuration policy is based upon whether the component is also annotated with the Meta Type Designate annotation.

  • Not annotated with Designate - The configuration policy is OPTIONAL.

  • Annotated with Designate(factory=false) - The configuration policy is OPTIONAL.

  • Annotated with Designate(factory=true) - The configuration policy is REQUIRE.

The configuration-policy attribute of the component element of a Component Description.

1.1

112.13.4.11 String[] configurationPid default "$"

The configuration PIDs for the configuration of this Component.

Each value specifies a configuration PID for this Component.

If no value is specified, the name of this Component is used as the configuration PID of this Component.

A special string ("$") can be used to specify the name of the component as a configuration PID. The NAME constant holds this special string. For example:

 @Component(configurationPid={"com.acme.system", Component.NAME})

Tools creating a Component Description from this annotation must replace the special string with the actual name of this Component.

The configuration-pid attribute of the component element of a Component Description.

1.2

112.13.4.12 ServiceScope scope default DEFAULT

The service scope for the service of this Component.

If not specified (and the deprecated servicefactory() element is not specified), the singleton service scope is used. If the factory() element is specified or the immediate() element is specified with true, this element can only be specified with the singleton service scope.

The scope attribute of the service element of a Component Description.

1.3

112.13.4.13 Reference[] reference default {}

The lookup strategy references of this Component.

To access references using the lookup strategy, Reference annotations are specified naming the reference and declaring the type of the referenced service. The referenced service can be accessed using one of the locateService methods of ComponentContext.

To access references using method injection, bind methods are annotated with Reference. To access references using field injection, fields are annotated with Reference. To access references using constructor injection, constructor parameters are annotated with Reference.

The reference element of a Component Description.

1.3

112.13.4.14 String[] factoryProperty default {}

Factory properties for this Factory Component.

Each factory property string is specified as "name=value". The type of the factory property value can be specified in the name as name:type=value. The type must be one of the factory property types supported by the type attribute of the factory-property element of a Component Description.

To specify a factory property with multiple values, use multiple name, value pairs. For example, {"foo=bar", "foo=baz"}.

If specified, the factory() element must also be specified to indicate the component is a Factory Component.

The factory-property element of a Component Description.

1.4

112.13.4.15 String[] factoryProperties default {}

Factory property entries for this Factory Component.

Specifies the name of an entry in the bundle whose contents conform to a standard Java Properties File. The entry is read and processed to obtain the factory properties and their values.

If specified, the factory() element must also be specified to indicate the component is a Factory Component.

The factory-properties element of a Component Description.

1.4

112.13.4.16 String NAME = "$"

Special string representing the name of this Component.

This string can be used in configurationPid() to specify the name of the component as a configuration PID. For example:

 @Component(configurationPid={"com.acme.system", Component.NAME})

Tools creating a Component Description from this annotation must replace the special string with the actual name of this Component.

1.3

112.13.5 @ComponentPropertyType

Identify the annotated annotation as a Component Property Type.

Component Property Types can be applied as annotations to the implementation class of the Component. They can also be used as activation objects which means they can be used as parameter types for the component's constructor and life cycle methods Activate, Deactivate, and Modified as well as activation fields.

Component Property Types do not have to be annotated with this annotation to be used as parameter types but they must be annotated with this annotation to be used as annotations on the implementation class of the Component.

This annotation is not processed at runtime by Service Component Runtime. It must be processed by tools and used to add a Component Description to the bundle.

Component Property Types.

1.4

CLASS

ANNOTATION_TYPE

112.13.6 enum ConfigurationPolicy

Configuration Policy for the Component annotation.

Controls whether component configurations must be satisfied depending on the presence of a corresponding Configuration object in the OSGi Configuration Admin service. A corresponding configuration is a Configuration object where the PID is the name of the component.

1.1

112.13.6.1 OPTIONAL

Use the corresponding Configuration object if present but allow the component to be satisfied even if the corresponding Configuration object is not present.

112.13.6.2 REQUIRE

There must be a corresponding Configuration object for the component configuration to become satisfied.

112.13.6.3 IGNORE

Always allow the component configuration to be satisfied and do not use the corresponding Configuration object even if it is present.

112.13.6.4 public String toString()

112.13.6.5 public static ConfigurationPolicy valueOf(String name)

112.13.6.6 public static ConfigurationPolicy[] values()

112.13.7 @Deactivate

Identify the annotated method as the deactivate method of a Service Component.

The annotated method is the deactivate method of the Component.

This annotation is not processed at runtime by Service Component Runtime. It must be processed by tools and used to add a Component Description to the bundle.

The deactivate attribute of the component element of a Component Description.

1.1

CLASS

METHOD

112.13.8 enum FieldOption

Field options for the Reference annotation.

1.3

112.13.8.1 UPDATE

The update field option is used to update the collection referenced by the field when there are changes to the bound services.

This field option can only be used when the field reference has dynamic policy and multiple cardinality.

112.13.8.2 REPLACE

The replace field option is used to replace the field value with a new value when there are changes to the bound services.

112.13.8.3 public String toString()

112.13.8.4 public static FieldOption valueOf(String name)

112.13.8.5 public static FieldOption[] values()

112.13.9 @Modified

Identify the annotated method as the modified method of a Service Component.

The annotated method is the modified method of the Component.

This annotation is not processed at runtime by Service Component Runtime. It must be processed by tools and used to add a Component Description to the bundle.

The modified attribute of the component element of a Component Description.

1.1

CLASS

METHOD

112.13.10 @Reference

Identify the annotated member or parameter as a reference of a Service Component.

When the annotation is applied to a method, the method is the bind method of the reference.

When the annotation is applied to a field, the field will contain the bound service(s) of the reference.

When the annotation is applied to a parameter of a constructor, the parameter will contain the bound service(s) of the reference.

This annotation is not processed at runtime by Service Component Runtime. It must be processed by tools and used to add a Component Description to the bundle.

In the generated Component Description for a component, the references must be ordered in ascending lexicographical order (using String.compareTo ) of the reference names.

The reference element of a Component Description.

CLASS

METHOD, FIELD, PARAMETER

112.13.10.1 String name default ""

The name of this reference.

The name of this reference must be specified when using this annotation in the Component.reference() element since there is no annotated member from which the name can be determined. If not specified, the name of this reference is based upon how this annotation is used:

  • Annotated method - If the method name begins with bind, set or add, that prefix is removed to create the name of the reference. Otherwise, the name of the reference is the method name.

  • Annotated field - The name of the reference is the field name.

  • Annotated constructor parameter - The name of the reference is the parameter name.

The name attribute of the reference element of a Component Description.

112.13.10.2 Class<?> service default Object.class

The type of the service for this reference.

The type of the service for this reference must be specified when using this annotation in the Component.reference() element since there is no annotated member from which the type of the service can be determined.

If not specified, the type of the service for this reference is based upon how this annotation is used:

  • Annotated method - The type of the service is the type of the first parameter of the method.

  • Annotated field - The type of the service is based upon the cardinality of the reference and the type of the field being annotated. If the cardinality is either 0..n, or 1..n, the type of the field must be one of java.util.Collection, java.util.List, or a subtype of java.util.Collection, so the type of the service is the generic type of the collection. If the cardinality is either 0..1 or 1..1, and the type of the field is java.util.Optional, the type of the service is the generic type of the java.util.Optional. Otherwise, the type of the service is the type of the field.

  • Annotated constructor parameter - The type of the service is based upon the cardinality of the reference and the type of the parameter being annotated. If the cardinality is either 0..n, or 1..n, the type of the parameter must be one of java.util.Collection or java.util.List, so the type of the service is the generic type of the collection. If the cardinality is either 0..1 or 1..1, and the type of the parameter is java.util.Optional, the type of the service is the generic type of the java.util.Optional. Otherwise, the type of the service is the type of the parameter.

The interface attribute of the reference element of a Component Description., AnyService

112.13.10.3 ReferenceCardinality cardinality default MANDATORY

The cardinality of this reference.

If not specified, the cardinality of this reference is based upon how this annotation is used:

  • Annotated method - The cardinality is 1..1.

  • Annotated field - The cardinality is based on the type of the field. If the type is either java.util.Collection, java.util.List, or a subtype of java.util.Collection, the cardinality is 0..n. If the type is java.util.Optional, the cardinality is 0..1. Otherwise the cardinality is 1..1.

  • Annotated constructor parameter - The cardinality is based on the type of the parameter. If the type is either java.util.Collection or java.util.List, the cardinality is 0..n. If the type is java.util.Optional, the cardinality is 0..1. Otherwise the cardinality is 1..1.

  • Component.reference() element - The cardinality is 1..1.

The cardinality attribute of the reference element of a Component Description.

112.13.10.4 ReferencePolicy policy default STATIC

The policy for this reference.

If not specified, the policy of this reference is based upon how this annotation is used:

  • Annotated method - The policy is STATIC.

  • Annotated field - The policy is based on the modifiers of the field. If the field is declared volatile, the policy is ReferencePolicy.DYNAMIC. Otherwise the policy is STATIC.

  • Annotated constructor parameter - The policy is STATIC. STATIC policy must be used for constructor parameters.

  • Component.reference() element - The policy is STATIC.

The policy attribute of the reference element of a Component Description.

112.13.10.5 String target default ""

The target property for this reference.

If not specified, no target property is set. A target property must be specified if the service() element refers to AnyService.

The target attribute of the reference element of a Component Description.

112.13.10.6 ReferencePolicyOption policyOption default RELUCTANT

The policy option for this reference.

If not specified, the RELUCTANT reference policy option is used.

The policy-option attribute of the reference element of a Component Description.

1.2

112.13.10.7 ReferenceScope scope default BUNDLE

The reference scope for this reference.

If not specified, the bundle reference scope is used.

The scope attribute of the reference element of a Component Description.

1.3

112.13.10.8 String bind default ""

The name of the bind method for this reference.

If specified and this reference annotates a method, the specified name must match the name of the annotated method.

If not specified, the name of the bind method is based upon how this annotation is used:

  • Annotated method - The name of the annotated method is the name of the bind method.

  • Annotated field - There is no bind method name.

  • Annotated constructor parameter - There is no bind method name.

  • Component.reference() element - There is no bind method name.

If there is a bind method name, the component must contain a method with that name.

The bind attribute of the reference element of a Component Description.

1.3

112.13.10.9 String updated default ""

The name of the updated method for this reference.

If not specified, the name of the updated method is based upon how this annotation is used:

  • Annotated method - The name of the updated method is created from the name of the annotated method. If the name of the annotated method begins with bind, set or add, that prefix is replaced with updated to create the name candidate for the updated method. Otherwise, updated is prefixed to the name of the annotated method to create the name candidate for the updated method. If the component type contains a method with the candidate name, the candidate name is used as the name of the updated method. To declare no updated method when the component type contains a method with the candidate name, the value "-" must be used.

  • Annotated field - There is no updated method name.

  • Annotated constructor parameter - There is no updated method name.

  • Component.reference() element - There is no updated method name.

If there is an updated method name, the component must contain a method with that name.

The updated attribute of the reference element of a Component Description.

1.2

112.13.10.10 String unbind default ""

The name of the unbind method for this reference.

If not specified, the name of the unbind method is based upon how this annotation is used:

  • Annotated method - The name of the unbind method is created from the name of the annotated method. If the name of the annotated method begins with bind, set or add, that prefix is replaced with unbind, unset or remove, respectively, to create the name candidate for the unbind method. Otherwise, un is prefixed to the name of the annotated method to create the name candidate for the unbind method. If the component type contains a method with the candidate name, the candidate name is used as the name of the unbind method. To declare no unbind method when the component type contains a method with the candidate name, the value "-" must be used.

  • Annotated field - There is no unbind method name.

  • Annotated constructor parameter - There is no unbind method name.

  • Component.reference() element - There is no unbind method name.

If there is an unbind method name, the component must contain a method with that name.

The unbind attribute of the reference element of a Component Description.

112.13.10.11 String field default ""

The name of the field for this reference.

If specified and this reference annotates a field, the specified name must match the name of the annotated field.

If not specified, the name of the field is based upon how this annotation is used:

  • Annotated method - There is no field name.

  • Annotated field - The name of the annotated field is the name of the field.

  • Annotated constructor parameter - There is no field name.

  • Component.reference() element - There is no field name.

If there is a field name, the component must contain a field with that name.

The field attribute of the reference element of a Component Description.

1.3

112.13.10.12 FieldOption fieldOption default REPLACE

The field option for this reference.

If not specified, the field option is based upon how this annotation is used:

  • Annotated method - There is no field option.

  • Annotated field - The field option is based upon the policy and cardinality of the reference and the modifiers of the field. If the policy is ReferencePolicy.DYNAMIC, the cardinality is 0..n or 1..n, and the field is declared final, the field option is FieldOption.UPDATE. Otherwise, the field option is FieldOption.REPLACE.

  • Annotated constructor parameter - There is no field option.

  • Component.reference() element - There is no field option.

The field-option attribute of the reference element of a Component Description.

1.3

112.13.10.13 int parameter default 0

The zero-based parameter number of the constructor parameter for this reference.

If specified and this reference annotates an constructor parameter, the specified value must match the zero-based parameter number of the annotated constructor parameter.

If not specified, the parameter number is based upon how this annotation is used:

  • Annotated method - There is no parameter number.

  • Annotated field - There is no parameter number.

  • Annotated constructor parameter - The zero-based parameter number of the parameter.

  • Component.reference() element - There is no parameter number.

If there is a parameter number, the component must declare a constructor that has a parameter having the zero-based parameter number.

The parameter attribute of the reference element of a Component Description., The init attribute of the component element of a Component Description.

1.4

112.13.10.14 CollectionType collectionType default SERVICE

The collection type for this reference.

If not specified, the collection type is based upon how this annotation is used:

  • Annotated method - There is no collection type.

  • Annotated field - The collection type is based upon the cardinality of the reference and the type of the field. If the cardinality is either 0..n or 1..n, the collection type is inferred from the generic type of the java.util.Collection. If the cardinality is either 0..1 or 1..1, and the type of the field is java.util.Optional, the collection type is inferred from the generic type of the java.util.Optional. Otherwise, there is no collection type

  • Annotated constructor method parameter - The collection type is based upon the cardinality of the reference and the type of the parameter. If the cardinality is either 0..n or 1..n, the collection type is inferred from the generic type of the java.util.Collection. If the cardinality is either 0..1 or 1..1, and the type of the parameter is java.util.Optional, the collection type is inferred from the generic type of the java.util.Optional. Otherwise, there is no collection type

  • Component.reference() element - There is no collection type.

The field-collection-type attribute of the reference element of a Component Description.

1.4

112.13.11 enum ReferenceCardinality

Cardinality for the Reference annotation.

Specifies if the reference is optional and if the component implementation support a single bound service or multiple bound services.

112.13.11.1 OPTIONAL

The reference is optional and unary. That is, the reference has a cardinality of 0..1.

112.13.11.2 MANDATORY

The reference is mandatory and unary. That is, the reference has a cardinality of 1..1.

112.13.11.3 MULTIPLE

The reference is optional and multiple. That is, the reference has a cardinality of 0..n.

112.13.11.4 AT_LEAST_ONE

The reference is mandatory and multiple. That is, the reference has a cardinality of 1..n.

112.13.11.5 public String toString()

112.13.11.6 public static ReferenceCardinality valueOf(String name)

112.13.11.7 public static ReferenceCardinality[] values()

112.13.12 enum ReferencePolicy

Policy for the Reference annotation.

112.13.12.1 STATIC

The static policy is the most simple policy and is the default policy. A component instance never sees any of the dynamics. Component configurations are deactivated before any bound service for a reference having a static policy becomes unavailable. If a target service is available to replace the bound service which became unavailable, the component configuration must be reactivated and bound to the replacement service.

112.13.12.2 DYNAMIC

The dynamic policy is slightly more complex since the component implementation must properly handle changes in the set of bound services. With the dynamic policy, SCR can change the set of bound services without deactivating a component configuration. If the component uses method injection to access services, then the component instance will be notified of changes in the set of bound services by calls to the bind and unbind methods.

112.13.12.3 public String toString()

112.13.12.4 public static ReferencePolicy valueOf(String name)

112.13.12.5 public static ReferencePolicy[] values()

112.13.13 enum ReferencePolicyOption

Policy option for the Reference annotation.

1.2

112.13.13.1 RELUCTANT

The reluctant policy option is the default policy option for both static and dynamic reference policies. When a new target service for a reference becomes available, references having the reluctant policy option for the static policy or the dynamic policy with a unary cardinality will ignore the new target service. References having the dynamic policy with a multiple cardinality will bind the new target service.

112.13.13.2 GREEDY

The greedy policy option is a valid policy option for both static and dynamic reference policies. When a new target service for a reference becomes available, references having the greedy policy option will bind the new target service.

112.13.13.3 public String toString()

112.13.13.4 public static ReferencePolicyOption valueOf(String name)

112.13.13.5 public static ReferencePolicyOption[] values()

112.13.14 enum ReferenceScope

Reference scope for the Reference annotation.

1.3

112.13.14.1 BUNDLE

A single service object is used for all references to the service in this bundle.

112.13.14.2 PROTOTYPE

If the bound service has prototype service scope, then each instance of the component with this reference can receive a unique instance of the service. If the bound service does not have prototype service scope, then this reference scope behaves the same as BUNDLE.

112.13.14.3 PROTOTYPE_REQUIRED

Bound services must have prototype service scope. Each instance of the component with this reference can receive a unique instance of the service.

112.13.14.4 public String toString()

112.13.14.5 public static ReferenceScope valueOf(String name)

112.13.14.6 public static ReferenceScope[] values()

112.13.15 @RequireServiceComponentRuntime

This annotation can be used to require the Service Component Runtime to process Declarative Services components. It can be used directly, or as a meta-annotation.

1.4

CLASS

TYPE, PACKAGE

112.13.16 enum ServiceScope

Service scope for the Component annotation.

1.3

112.13.16.1 SINGLETON

When the component is registered as a service, it must be registered as a bundle scope service but only a single instance of the component must be used for all bundles using the service.

112.13.16.2 BUNDLE

When the component is registered as a service, it must be registered as a bundle scope service and an instance of the component must be created for each bundle using the service.

112.13.16.3 PROTOTYPE

When the component is registered as a service, it must be registered as a prototype scope service and an instance of the component must be created for each distinct request for the service.

112.13.16.4 DEFAULT

Default element value for annotation. This is used to distinguish the default value for an element and should not otherwise be used.

112.13.16.5 public String toString()

112.13.16.6 public static ServiceScope valueOf(String name)

112.13.16.7 public static ServiceScope[] values()

112.14 org.osgi.service.component.runtime

Version 1.5

Service Component Runtime Package Version 1.5.

Bundles wishing to use this package must list the package in the Import-Package header of the bundle's manifest. This package has two types of users: the consumers that use the API in this package and the providers that implement the API in this package.

Example import for consumers using the API in this package:

Import-Package: org.osgi.service.component.runtime; version="[1.5,2.0)"

Example import for providers implementing the API in this package:

Import-Package: org.osgi.service.component.runtime; version="[1.5,1.6)"

112.14.1 Summary

  • ServiceComponentRuntime - The ServiceComponentRuntime service represents the Declarative Services actor, known as Service Component Runtime (SCR), that manages the service components and their life cycle.

112.14.2 public interface ServiceComponentRuntime

The ServiceComponentRuntime service represents the Declarative Services actor, known as Service Component Runtime (SCR), that manages the service components and their life cycle. The ServiceComponentRuntime service allows introspection of the components managed by Service Component Runtime.

This service differentiates between a ComponentDescriptionDTO and a ComponentConfigurationDTO. A ComponentDescriptionDTO is a representation of a declared component description. A ComponentConfigurationDTO is a representation of an actual instance of a declared component description parameterized by component properties.

This service must be registered with a Constants.SERVICE_CHANGECOUNT service property that must be updated each time the SCR DTOs available from this service change.

Access to this service requires the ServicePermission[ServiceComponentRuntime, GET] permission. It is intended that only administrative bundles should be granted this permission to limit access to the potentially intrusive methods provided by this service.

1.3

Thread-safe

Consumers of this API must not implement this type

112.14.2.1 public Promise<Void> disableComponent(ComponentDescriptionDTO description)

The component description to disable. Must not be null.

Disables the specified component description.

If the specified component description is currently disabled, this method has no effect.

This method must return after changing the enabled state of the specified component description. Any actions that result from this, such as activating or deactivating a component configuration, must occur asynchronously to this method call.

A promise that will be resolved when the actions that result from changing the enabled state of the specified component have completed. If the provided description does not belong to an active bundle, a failed promise is returned.

isComponentEnabled(ComponentDescriptionDTO)

112.14.2.2 public Promise<Void> enableComponent(ComponentDescriptionDTO description)

The component description to enable. Must not be null.

Enables the specified component description.

If the specified component description is currently enabled, this method has no effect.

This method must return after changing the enabled state of the specified component description. Any actions that result from this, such as activating or deactivating a component configuration, must occur asynchronously to this method call.

A promise that will be resolved when the actions that result from changing the enabled state of the specified component have completed. If the provided description does not belong to an active bundle, a failed promise is returned.

isComponentEnabled(ComponentDescriptionDTO)

112.14.2.3 public Collection<ComponentConfigurationDTO> getComponentConfigurationDTOs(ComponentDescriptionDTO description)

The component description. Must not be null.

Returns the component configurations for the specified component description.

A collection containing a snapshot of the current component configurations for the specified component description. An empty collection is returned if there are none or if the provided component description does not belong to an active bundle.

112.14.2.4 public ComponentDescriptionDTO getComponentDescriptionDTO(Bundle bundle, String name)

The bundle declaring the component description. Must not be null.

The name of the component description. Must not be null.

Returns the ComponentDescriptionDTO declared with the specified name by the specified bundle.

Only component descriptions from active bundles are returned. null if no such component is declared by the given bundle or the bundle is not active.

The declared component description or null if the specified bundle is not active or does not declare a component description with the specified name.

112.14.2.5 public Collection<ComponentDescriptionDTO> getComponentDescriptionDTOs(Bundle... bundles)

The bundles whose declared component descriptions are to be returned. Specifying no bundles, or the equivalent of an empty Bundle array, will return the declared component descriptions from all active bundles.

Returns the component descriptions declared by the specified active bundles.

Only component descriptions from active bundles are returned. If the specified bundles have no declared components or are not active, an empty collection is returned.

The declared component descriptions of the specified active bundles. An empty collection is returned if there are no component descriptions for the specified active bundles.

112.14.2.6 public boolean isComponentEnabled(ComponentDescriptionDTO description)

The component description. Must not be null.

Returns whether the specified component description is currently enabled.

The enabled state of a component description is initially set by the enabled attribute of the component description.

true if the specified component description is currently enabled. Otherwise, false.

enableComponent(ComponentDescriptionDTO), disableComponent(ComponentDescriptionDTO), ComponentContext.disableComponent(String), ComponentContext.enableComponent(String)

112.15 org.osgi.service.component.runtime.dto

Version 1.5

Service Component Runtime Data Transfer Objects Package Version 1.5.

Bundles wishing to use this package must list the package in the Import-Package header of the bundle's manifest. This package has two types of users: the consumers that use the API in this package and the providers that implement the API in this package.

Example import for consumers using the API in this package:

Import-Package: org.osgi.service.component.runtime.dto; version="[1.5,2.0)"

Example import for providers implementing the API in this package:

Import-Package: org.osgi.service.component.runtime.dto; version="[1.5,1.6)"

112.15.1 Summary

112.15.2 public class ComponentConfigurationDTO
extends DTO

A representation of an actual instance of a declared component description parameterized by component properties.

1.3

Not Thread-safe

112.15.2.1 public static final int ACTIVE = 8

The component configuration is active.

This is the normal operational state of a component configuration.

112.15.2.2 public ComponentDescriptionDTO description

The representation of the component configuration's component description.

112.15.2.3 public static final int FAILED_ACTIVATION = 16

The component configuration failed to activate.

This means the component configuration is satisfied but that either:

  • an exception occurred loading the implementation class,

  • the static initializer threw an exception,

  • the constructor threw an exception, or

  • the activate method threw an exception.

The failure information from the exception is available from failure.

1.4

112.15.2.4 public String failure

The failure information if the component configuration state is FAILED_ACTIVATION.

This is the failure exception converted to a String using:

 StringWriter sw = new StringWriter();
 exception.printStackTrace(new PrintWriter(sw));
 sw.toString();

This must be null if the component configuration state is not FAILED_ACTIVATION.

1.4

112.15.2.5 public long id

The id of the component configuration.

The id is a non-persistent, unique value assigned at runtime. The id is also available as the component.id component property. The value of this field is unspecified if the state of this component configuration is unsatisfied.

112.15.2.6 public Map<String, Object> properties

The component properties for the component configuration.

ComponentContext.getProperties()

112.15.2.7 public static final int SATISFIED = 4

The component configuration is satisfied.

Any services declared by the component description are registered.

112.15.2.8 public SatisfiedReferenceDTO[] satisfiedReferences

The satisfied references.

Each SatisfiedReferenceDTO in the array represents a satisfied reference of the component configuration. The array must be empty if the component configuration has no satisfied references.

112.15.2.9 public ServiceReferenceDTO service

The registered service of the component configuration.

This must be non-null if the component configuration is registered as a service. Otherwise it must be null.

1.4

112.15.2.10 public int state

The current state of the component configuration.

This is one of UNSATISFIED_CONFIGURATION, UNSATISFIED_REFERENCE, SATISFIED, ACTIVE, or FAILED_ACTIVATION.

112.15.2.11 public static final int UNSATISFIED_CONFIGURATION = 1

The component configuration is unsatisfied due to a missing required configuration.

112.15.2.12 public static final int UNSATISFIED_REFERENCE = 2

The component configuration is unsatisfied due to an unsatisfied reference.

112.15.2.13 public UnsatisfiedReferenceDTO[] unsatisfiedReferences

The unsatisfied references.

Each UnsatisfiedReferenceDTO in the array represents an unsatisfied reference of the component configuration. The array must be empty if the component configuration has no unsatisfied references.

112.15.2.14 public ComponentConfigurationDTO()

112.15.3 public class ComponentDescriptionDTO
extends DTO

A representation of a declared component description.

1.3

Not Thread-safe

112.15.3.1 public String activate

The name of the activate method.

This is declared in the activate attribute of the component element. This must be null if the component description does not declare an activate method name.

112.15.3.2 public String[] activationFields

The activation fields.

These are declared in the activation-fields attribute of the component element. The array must be empty if the component description does not declare any activation fields.

1.4

112.15.3.3 public BundleDTO bundle

The bundle declaring the component description.

112.15.3.4 public String[] configurationPid

The configuration pids.

These are declared in the configuration-pid attribute of the component element. This must contain the default configuration pid if the component description does not declare a configuration pid.

112.15.3.5 public String configurationPolicy

The configuration policy.

This is declared in the configuration-policy attribute of the component element. This must be the default configuration policy if the component description does not declare a configuration policy.

112.15.3.6 public String deactivate

The name of the deactivate method.

This is declared in the deactivate attribute of the component element. This must be null if the component description does not declare a deactivate method name.

112.15.3.7 public boolean defaultEnabled

The initial enabled state.

This is declared in the enabled attribute of the component element.

112.15.3.8 public String factory

The component factory name.

This is declared in the factory attribute of the component element. This must be null if the component description is not declared as a factory component.

112.15.3.9 public Map<String, Object> factoryProperties

The factory properties.

These are declared in the component description by the factory-property and factory-properties elements. This must be null if the component description is not declared as a factory component.

1.4

112.15.3.10 public boolean immediate

The immediate state.

This is declared in the immediate attribute of the component element.

112.15.3.11 public String implementationClass

The fully qualified name of the implementation class.

This is declared in the class attribute of the implementation element.

112.15.3.12 public int init

The constructor parameter count.

This is declared in the init attribute of the component element. This must be 0 if the component description does not declare an init attribute.

1.4

112.15.3.13 public String modified

The name of the modified method.

This is declared in the modified attribute of the component element. This must be null if the component description does not declare a modified method name.

112.15.3.14 public String name

The name of the component.

This is declared in the name attribute of the component element. This must be the default name if the component description does not declare a name.

112.15.3.15 public Map<String, Object> properties

The component properties.

These are declared in the component description by the property and properties elements as well as the target attribute of the reference elements.

112.15.3.16 public ReferenceDTO[] references

The referenced services.

These are declared in the reference elements. The array must be empty if the component description does not declare references to any services.

112.15.3.17 public String scope

The service scope.

This is declared in the scope attribute of the service element. This must be null if the component description does not declare any service interfaces.

112.15.3.18 public String[] serviceInterfaces

The fully qualified names of the service interfaces.

These are declared in the interface attribute of the provide elements. The array must be empty if the component description does not declare any service interfaces.

112.15.3.19 public ComponentDescriptionDTO()

112.15.4 public class ReferenceDTO
extends DTO

A representation of a declared reference to a service.

1.3

Not Thread-safe

112.15.4.1 public String bind

The name of the bind method of the reference.

This is declared in the bind attribute of the reference element. This must be null if the component description does not declare a bind method for the reference.

112.15.4.2 public String cardinality

The cardinality of the reference.

This is declared in the cardinality attribute of the reference element. This must be the default cardinality if the component description does not declare a cardinality for the reference.

112.15.4.3 public String collectionType

The collection type for the reference.

This is declared in the field-collection-type attribute of the reference element. This must be null if the component description does not declare a collection type for the reference.

1.4

112.15.4.4 public String field

The name of the field of the reference.

This is declared in the field attribute of the reference element. This must be null if the component description does not declare a field for the reference.

112.15.4.5 public String fieldOption

The field option of the reference.

This is declared in the field-option attribute of the reference element. This must be null if the component description does not declare a field for the reference.

112.15.4.6 public String interfaceName

The service interface of the reference.

This is declared in the interface attribute of the reference element.

112.15.4.7 public String name

The name of the reference.

This is declared in the name attribute of the reference element. This must be the default name if the component description does not declare a name for the reference.

112.15.4.8 public Integer parameter

The zero-based parameter number of the constructor parameter for the reference.

This is declared in the parameter attribute of the reference element. This must be null if the component description does not declare a parameter number for the reference.

1.4

112.15.4.9 public String policy

The policy of the reference.

This is declared in the policy attribute of the reference element. This must be the default policy if the component description does not declare a policy for the reference.

112.15.4.10 public String policyOption

The policy option of the reference.

This is declared in the policy-option attribute of the reference element. This must be the default policy option if the component description does not declare a policy option for the reference.

112.15.4.11 public String scope

The scope of the reference.

This is declared in the scope attribute of the reference element. This must be the default scope if the component description does not declare a scope for the reference.

112.15.4.12 public String target

The target of the reference.

This is declared in the target attribute of the reference element. This must be null if the component description does not declare a target for the reference.

112.15.4.13 public String unbind

The name of the unbind method of the reference.

This is declared in the unbind attribute of the reference element. This must be null if the component description does not declare an unbind method for the reference.

112.15.4.14 public String updated

The name of the updated method of the reference.

This is declared in the updated attribute of the reference element. This must be null if the component description does not declare an updated method for the reference.

112.15.4.15 public ReferenceDTO()

112.15.5 public class SatisfiedReferenceDTO
extends DTO

A representation of a satisfied reference.

1.3

Not Thread-safe

112.15.5.1 public ServiceReferenceDTO[] boundServices

The bound services.

Each ServiceReferenceDTO in the array represents a service bound to the satisfied reference. The array must be empty if there are no bound services.

112.15.5.2 public String name

The name of the declared reference.

This is declared in the name attribute of the reference element of the component description.

ReferenceDTO.name

112.15.5.3 public String target

The target property of the satisfied reference.

This is the value of the component property whose name is the concatenation of the declared reference name and ".target". This must be null if no target property is set for the reference.

112.15.5.4 public SatisfiedReferenceDTO()

112.15.6 public class UnsatisfiedReferenceDTO
extends DTO

A representation of an unsatisfied reference.

1.3

Not Thread-safe

112.15.6.1 public String name

The name of the declared reference.

This is declared in the name attribute of the reference element of the component description.

ReferenceDTO.name

112.15.6.2 public String target

The target property of the unsatisfied reference.

This is the value of the component property whose name is the concatenation of the declared reference name and ".target". This must be null if no target property is set for the reference.

112.15.6.3 public ServiceReferenceDTO[] targetServices

The target services.

Each ServiceReferenceDTO in the array represents a target service for the reference. The array must be empty if there are no target services. The upper bound on the number of target services in the array is the upper bound on the cardinality of the reference.

112.15.6.4 public UnsatisfiedReferenceDTO()

112.16 org.osgi.service.component.propertytypes

Version 1.5

Component Property Types Package Version 1.5.

When used as annotations, component property types are processed by tools to generate Component Descriptions which are used at runtime.

Bundles wishing to use this package at runtime must list the package in the Import-Package header of the bundle's manifest.

Example import for consumers using the API in this package:

Import-Package: org.osgi.service.component.propertytypes; version="[1.5,2.0)"

112.16.1 Summary

112.16.2 @ExportedService

Component Property Type for the remote service properties for an exported service.

This annotation can be used on a Component to declare the values of the remote service properties for an exported service.

Component Property Types, Remote Services Specification

1.4

CLASS

TYPE

112.16.2.1 Class<?>[] service_exported_interfaces

Service property marking the service for export. It defines the interfaces under which the service can be exported.

If an empty array is specified, the property is not added to the component description.

The exported service interfaces.

Constants.SERVICE_EXPORTED_INTERFACES

112.16.2.2 String[] service_exported_configs default {}

Service property identifying the configuration types that should be used to export the service.

If an empty array is specified, the default value, the property is not added to the component description.

The configuration types.

Constants.SERVICE_EXPORTED_CONFIGS

112.16.2.3 String[] service_exported_intents default {}

Service property identifying the intents that the distribution provider must implement to distribute the service.

If an empty array is specified, the default value, the property is not added to the component description.

The intents that the distribution provider must implement to distribute the service.

Constants.SERVICE_EXPORTED_INTENTS

112.16.2.4 String[] service_exported_intents_extra default {}

Service property identifying the extra intents that the distribution provider must implement to distribute the service.

If an empty array is specified, the default value, the property is not added to the component description.

The extra intents that the distribution provider must implement to distribute the service.

Constants.SERVICE_EXPORTED_INTENTS_EXTRA

112.16.2.5 String[] service_intents default {}

Service property identifying the intents that this service implements.

If an empty array is specified, the default value, the property is not added to the component description.

The intents that the service implements.

Constants.SERVICE_INTENTS

112.16.3 @SatisfyingConditionTarget

Component Property Type for the osgi.ds.satisfying.condition.target reference property.

This annotation can be used on a Component to declare the value of the target property for the component's satisfying condition reference if a value other than the default value is desired.

Component Property Types

1.5

CLASS

TYPE

112.16.3.1 String value default "(osgi.condition.id=true)"

Filter expression to select the component's satisfying condition.

The filter expression to select the component's satisfying condition.

112.16.3.2 String PREFIX_ = "osgi.ds."

Prefix for the property name. This value is prepended to each property name.

112.16.4 @ServiceDescription

Component Property Type for the service.description service property.

This annotation can be used on a Component to declare the value of the Constants.SERVICE_DESCRIPTION service property.

Component Property Types

1.4

CLASS

TYPE

112.16.4.1 String value

Service property identifying a service's description.

The service description.

Constants.SERVICE_DESCRIPTION

112.16.5 @ServiceRanking

Component Property Type for the service.ranking service property.

This annotation can be used on a Component to declare the value of the Constants.SERVICE_RANKING service property.

Component Property Types

1.4

CLASS

TYPE

112.16.5.1 int value

Service property identifying a service's ranking.

The service ranking.

Constants.SERVICE_RANKING

112.16.6 @ServiceVendor

Component Property Type for the service.vendor service property.

This annotation can be used on a Component to declare the value of the Constants.SERVICE_VENDOR service property.

Component Property Types

1.4

CLASS

TYPE

112.16.6.1 String value

Service property identifying a service's vendor.

The service vendor.

Constants.SERVICE_VENDOR

112.17 References

[1]Automating Service Dependency Management in a Service-Oriented Component ModelHumberto Cervantes, Richard S. Hall, Proceedings of the Sixth Component-Based Software Engineering Workshop, May 2003, pp. 91-96
https://www.researchgate.net/publication/238655490_Automating_Service_Dependency_Management_in_a_Service-Oriented_Component_Model

[2]Service BinderHumberto Cervantes, Richard S. Hall
http://gravity.sourceforge.net/servicebinder

[4]Extensible Markup Language (XML) 1.0https://www.w3.org/TR/REC-xml/

[5]OSGi XML Schemashttps://docs.osgi.org/xmlns/

[6]The Java Virtual Machine Specification, Java SE 8 Editionhttps://docs.oracle.com/javase/specs/jvms/se8/html/index.html

[7]The Java Language Specification, Java SE 8 Editionhttps://docs.oracle.com/javase/specs/jls/se8/html/index.html