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.
-
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.
-
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.
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 thescope
attribute of theservice
element isbundle
, 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 thescope
attribute of theservice
element isprototype
, then, for each distinct request for the service object, such as viaServiceObjects
, 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 thecomponent
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 aservice
element, then as each component configuration is activated, SCR will register it as a service.
-
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.
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.
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.
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.
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.
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.
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.
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 thename
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.
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 thepolicy
isdynamic
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 implementComparable
with thecompareTo
method comparing service property maps using an ordering which is the same as the natural ordering ofServiceReference
s as specified inServiceReference.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.
-
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. -
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.
-
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. -
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. -
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. -
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'sinterface
attribute,org.osgi.framework.ServiceReference
, ComponentServiceObjects, orjava.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'sinterface
attribute isorg.osgi.framework.ServiceReference
, ComponentServiceObjects, orjava.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.
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'sinterface
attribute isorg.osgi.service.component.AnyService
, then the actual service type is considered to bejava.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 implementComparable
with thecompareTo
method comparing service property maps using an ordering which is the same as the natural ordering ofServiceReference
s as specified inServiceReference.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 implementComparable
with thecompareTo
method comparing the service property map key using an ordering which is the same as the natural ordering ofServiceReference
s as specified inServiceReference.compareTo
. -
Optional
- An Optional holding one of the above types. The type of object held in the Optional is specified by thefield-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 theupdate
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 implementComparable
, 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 implementComparable
, 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.
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:
-
If the constructor is not public, then the constructor must not be considered.
-
If the constructor has a parameter count that does not match the value of the
init
attribute in thecomponent
element, then the constructor must not be considered. If the value of theinit
attribute is 0, the default value, then the public no-parameter constructor must be used. -
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. -
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.
-
If only a single constructor remains, this constructor must be used to construct the component instance.
-
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!");
}
}
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");
}
}
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.
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.
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.
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.
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 |
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.
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
ServiceReference
s 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 ServiceReference
s as
specified in ServiceReference.compareTo
. The new
collection may be empty if the reference has optional cardinality and
there are no bound services.
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
orList
, SCR will set the field value to a new mutable empty collection or list object, respectively. If the field is declared with thefinal
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 byCollection.remove
for the old element.
The collection may be empty if the reference has optional cardinality and there are no bound 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.
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>
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.
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”));
}
}
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.
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.
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.
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.
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.
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
|
enabled |
enabled |
Controls whether the component is
enabled when the bundle is started. The
default value is |
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
|
configuration-policy |
Controls whether component configurations must be
satisfied depending on the presence of a corresponding
|
|
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
|
activate |
Activate |
Specifies the name of the method to call when a
component configuration is activated. The default value of this
attribute is 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 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 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 The Modified annotation must be applied to at most one method which is to be used as the modified method. |
The implementation
element is required and defines
the name of the component implementation class. The single attribute is
defined in the following table.
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.
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 |
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 |
|
type |
The type of the property. Defines how to interpret the value. The type must be one of the following Java types:
|
|
<body> |
If the Values must be
placed one per line and blank lines are ignored. Parsing of each
value is done by the |
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 |
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.
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 |
Controls the scope of the provided service. If set
to |
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 |
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,
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 { ... }
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 |
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 The |
|
interface |
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
The special
|
|
cardinality |
Specifies if the reference is optional and if the component implementation support a single bound service or multiple bound services. See Reference Cardinality. |
|
policy |
The policy declares the assumption of the component about dynamicity. See Reference Policy. |
|
policy-option |
Defines the policy when a better service becomes available. See Reference Policy. |
|
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 |
The reference scope for this reference. See Reference Scope. |
|
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 The
|
|
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 |
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
|
|
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 The
|
|
field-option |
Defines how the field value must be managed. This
is ignored if the |
|
field-collection-type |
Defines the types of elements in the collection or
Optional referenced by the field value or constructor parameter.
This is ignored if the The |
|
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 The
|
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() { ... }
}
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 |
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 |
|
type |
The type of the factory property. Defines how to interpret the value. The type must be one of the following Java types:
|
|
<body> |
If the Values
must be placed one per line and blank lines are ignored. Parsing
of each value is done by the |
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 |
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.
-
factoryProperty element of the Component annotation.
-
factoryProperties element of the Component annotation.
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
.
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 aConfiguration
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.
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.
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.
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 thefactory
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.
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.
Activating a component configuration consists of the following steps:
-
Load the component implementation class.
-
Compute the bound services. See Bound Services.
-
Create the component context. See Component Context.
-
Construct the component instance. See Constructor Injection.
-
Set the activation fields, if any. See Activation Objects.
-
Bind the bound services. See Binding Services.
-
Call the
activate
method, if any. See Activate Method. Calling theactivate
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.
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.
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.
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.
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.
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:
-
The method takes a single parameter and the type of the parameter is
org.osgi.service.component.ComponentContext
. -
The method takes a single parameter and the type of the parameter is
org.osgi.framework.BundleContext
. -
The method takes a single parameter and the type of the parameter is a component property type.
-
The method takes a single parameter and the type of the parameter is
java.util.Map
. -
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.
-
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.
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.
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.
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:
-
Update the component context for the component configuration with the modified configuration properties.
-
Call the modified method. See Modified Method.
-
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.
-
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.
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:
-
The method takes a single parameter and the type of the parameter is
org.osgi.service.component.ComponentContext
. -
The method takes a single parameter and the type of the parameter is
org.osgi.framework.BundleContext
. -
The method takes a single parameter and the type of the parameter is a component property type.
-
The method takes a single parameter and the type of the parameter is
java.util.Map
. -
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.
-
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.
Deactivating a component configuration consists of the following steps:
-
Call the deactivate method, if present. See Deactivate Method.
-
Unbind any bound services. See Unbinding.
-
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:
-
DEACTIVATION_REASON_UNSPECIFIED - Unspecified.
-
DEACTIVATION_REASON_DISABLED - The component was disabled.
-
DEACTIVATION_REASON_REFERENCE - A reference became unsatisfied.
-
DEACTIVATION_REASON_CONFIGURATION_MODIFIED - A configuration was changed.
-
DEACTIVATION_REASON_CONFIGURATION_DELETED - A configuration was deleted.
-
DEACTIVATION_REASON_DISPOSED - The component was disposed.
-
DEACTIVATION_REASON_BUNDLE_STOPPED - The bundle was stopped.
Once the component configuration is deactivated, SCR must discard all references to the component instance and component context associated with the activation.
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
orInteger
- The reason the component configuration is being deactivated. See Deactivation.
A suitable method is selected using the following priority:
-
The method takes a single parameter and the type of the parameter is
org.osgi.service.component.ComponentContext
. -
The method takes a single parameter and the type of the parameter is
org.osgi.framework.BundleContext
. -
The method takes a single parameter and the type of the parameter is a component property type.
-
The method takes a single parameter and the type of the parameter is
java.util.Map
. -
The method takes a single parameter and the type of the parameter is
int
. -
The method takes a single parameter and the type of the parameter is
java.lang.Integer
. -
The method takes two or more parameters and the type of each parameter must be one of the activation object types,
int
orjava.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. -
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.
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
.
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:
-
A bundle with the
example.Binding
component is started. At that time there is a Log Servicel1
and a Http Serviceh1
registered. -
The Http Service
h1
is unregistered -
A new Http Service
h2
is registered -
The Log Service
h1
is unregistered.
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):
-
Properties specified in the argument of the
ComponentFactory.newInstance
method. This is only applicable for factory components. -
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 thecomponent
element. See Component Element. If noconfiguration-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. -
Properties specified in the component description via
property
andproperties
elements. Properties specified later in the component description override properties that have the same name specified earlier. See Property and Properties Elements. -
Target properties specified in the component description via the
target
attribute ofreference
elements. See Target Property. The value of thetarget
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.
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.
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.
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.
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.
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 toignore
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 theComponentFactory.newInstance
method will be used. -
Not Satisfied - If the component's
configuration-policy
is set torequire
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 tooptional
, the component configuration must be satisfied without the configurations PIDs which match a factory PID. If theconfiguration-policy
is set torequire
, 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)
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.
For configuration-policy
of ignore
,
component configurations are unaffected by configuration changes since
the component properties do not include properties from
Configuration
objects.
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.
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.
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.
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.
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.
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) { ... }
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.
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 thePREFIX_
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 thePREFIX_
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.
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.
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.
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.
-
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 generatedproperty
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:-
The component property types used as parameters to the constructor.
-
The component property types used as activation fields. The fields are processed in lexicographical order, using
String.compareTo
, of the field names. -
The component property types used as parameters to the activate method.
-
The component property types used as parameters to the modified method.
-
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. -
-
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 generatedproperty
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 theRuntimeVisibleAnnotations
andRuntimeInvisibleAnnotations
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 differentRetentionPolicy
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. -
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.
Service Component Runtime (SCR) is the actor that manages the components and their life cycle and allows introspection of the components.
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.
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.
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
.
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.
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.
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 returnsfalse
. -
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.
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.
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 theorg.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 sameorg.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 nameosgi.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 nameosgi.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 theorg.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.
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.
When Java permissions are enabled, SCR must perform the following security procedures.
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.
SCR requires AdminPermission[*,CONTEXT]
because it
needs access to the bundle's Bundle Context object with the
Bundle.getBundleContext()
method.
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.
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.
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.
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)"
-
AnyService
- A marker type whose name is used in theinterface
attribute of areference
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 thefactory
attribute on itscomponent
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.
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 thereference
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
Defines standard names for Service Component constants.
Consumers of this API must not implement this type
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
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
.
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.
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
.
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
The component configuration was deactivated because the bundle was stopped.
1.1
The component configuration was deactivated because its configuration was deleted.
1.1
The component configuration was deactivated because its configuration was changed.
1.1
The component configuration was deactivated because the component was disabled.
1.1
The component configuration was deactivated because the component was disposed.
1.1
The component configuration was deactivated because a reference became unsatisfied.
1.1
The reason the component configuration was deactivated is unspecified.
1.1
Reference name for a component's satisfying condition.
1.5
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
.
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.
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
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.
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.
Returns the BundleContext
of the bundle which declares this
component.
The BundleContext
of the bundle declares this component.
<S>
Returns the Component Instance object for the component instance associated with this Component Context.
The Component Instance object for the component instance.
Returns the component properties for this Component Context.
The properties for this Component Context. The Dictionary is read only and cannot be modified.
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.
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"
orservicescope="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
.
<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.
<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.
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.
Unchecked exception which may be thrown by Service Component Runtime.
The message for the exception.
The cause of the exception. May be null
.
Construct a new ComponentException with the specified message and cause.
The message for the exception.
Construct a new ComponentException with the specified message.
The cause of the exception. May be null
.
Construct a new ComponentException with the specified cause.
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.
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.
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
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.
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
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.
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
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.
Returns the ServiceReference for the service associated with this
ComponentServiceObjects
object.
The ServiceReference for the service associated with this
ComponentServiceObjects
object.
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.
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.
-
Activate
- Identify the annotated member as part of the activation of a Service Component. -
CollectionType
- Collection types for the Reference annotation. -
Component
- Identify the annotated class as a Service Component. -
ComponentPropertyType
- Identify the annotated annotation as a Component Property Type. -
ConfigurationPolicy
- Configuration Policy for the Component annotation. -
Deactivate
- Identify the annotated method as thedeactivate
method of a Service Component. -
FieldOption
- Field options for the Reference annotation. -
Modified
- Identify the annotated method as themodified
method of a Service Component. -
Reference
- Identify the annotated member or parameter as a reference of a Service Component. -
ReferenceCardinality
- Cardinality for the Reference annotation. -
ReferencePolicy
- Policy for the Reference annotation. -
ReferencePolicyOption
- Policy option for the Reference annotation. -
ReferenceScope
- Reference scope for the Reference annotation. -
RequireServiceComponentRuntime
- This annotation can be used to require the Service Component Runtime to process Declarative Services components. -
ServiceScope
- Service scope for the Component annotation.
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
Collection types for the Reference annotation.
1.4
The service collection type is used to indicate the collection holds the bound service objects.
This is the default collection type.
The reference collection type is used to indicate the collection holds Service References for the bound services.
The serviceobjects collection type is used to indicate the collection holds Component Service Objects for the bound services.
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 ServiceReference
s as specified in
ServiceReference.compareTo
.
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
ServiceReference
s as specified in
ServiceReference.compareTo
.
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
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.
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.
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.
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().
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.
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.
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.
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.
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.
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.
The configuration-policy attribute of the component element of a Component Description.
1.1
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
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
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
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
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
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
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
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
Use the corresponding Configuration object if present but allow the component to be satisfied even if the corresponding Configuration object is not present.
There must be a corresponding Configuration object for the component configuration to become satisfied.
Always allow the component configuration to be satisfied and do not use the corresponding Configuration object even if it is present.
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
Field options for the Reference annotation.
1.3
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.
The replace field option is used to replace the field value with a new value when there are changes to the bound services.
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
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
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
oradd
, 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.
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 ofjava.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 isjava.util.Optional
, the type of the service is the generic type of thejava.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
orjava.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 isjava.util.Optional
, the type of the service is the generic type of thejava.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
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 ofjava.util.Collection
, the cardinality is 0..n. If the type isjava.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
orjava.util.List
, the cardinality is 0..n. If the type isjava.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.
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.
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.
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
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
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
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
oradd
, that prefix is replaced withupdated
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
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
oradd
, that prefix is replaced withunbind
,unset
orremove
, 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.
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
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
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
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 isjava.util.Optional
, the collection type is inferred from the generic type of thejava.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 isjava.util.Optional
, the collection type is inferred from the generic type of thejava.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
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.
The reference is optional and unary. That is, the reference has a
cardinality of 0..1
.
The reference is mandatory and unary. That is, the reference has a
cardinality of 1..1
.
The reference is optional and multiple. That is, the reference has a
cardinality of 0..n
.
The reference is mandatory and multiple. That is, the reference has a
cardinality of 1..n
.
Policy for the Reference annotation.
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.
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.
Policy option for the Reference annotation.
1.2
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.
Reference scope for the Reference annotation.
1.3
A single service object is used for all references to the service in this bundle.
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.
Bound services must have prototype service scope. Each instance of the component with this reference can receive a unique instance of the service.
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
Service scope for the Component annotation.
1.3
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.
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.
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.
Default element value for annotation. This is used to distinguish the default value for an element and should not otherwise be used.
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)"
-
ServiceComponentRuntime
- TheServiceComponentRuntime
service represents the Declarative Services actor, known as Service Component Runtime (SCR), that manages the service components and their life cycle.
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
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.
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.
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.
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.
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.
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)
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)"
-
ComponentConfigurationDTO
- A representation of an actual instance of a declared component description parameterized by component properties. -
ComponentDescriptionDTO
- A representation of a declared component description. -
ReferenceDTO
- A representation of a declared reference to a service. -
SatisfiedReferenceDTO
- A representation of a satisfied reference. -
UnsatisfiedReferenceDTO
- A representation of an unsatisfied reference.
A representation of an actual instance of a declared component description parameterized by component properties.
1.3
Not Thread-safe
The component configuration is active.
This is the normal operational state of a component configuration.
The representation of the component configuration's component description.
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
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
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.
The component properties for the component configuration.
The component configuration is satisfied.
Any services declared by the component description are registered.
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.
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
The current state of the component configuration.
This is one of UNSATISFIED_CONFIGURATION, UNSATISFIED_REFERENCE, SATISFIED, ACTIVE, or FAILED_ACTIVATION.
The component configuration is unsatisfied due to a missing required configuration.
The component configuration is unsatisfied due to an unsatisfied reference.
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.
A representation of a declared component description.
1.3
Not Thread-safe
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.
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
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.
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.
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.
The initial enabled state.
This is declared in the enabled
attribute of the
component
element.
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.
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
The immediate state.
This is declared in the immediate
attribute of the
component
element.
The fully qualified name of the implementation class.
This is declared in the class
attribute of the
implementation
element.
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
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.
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.
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.
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.
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.
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.
A representation of a declared reference to a service.
1.3
Not Thread-safe
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.
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.
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
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.
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.
The service interface of the reference.
This is declared in the interface
attribute of the
reference
element.
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.
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
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.
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.
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.
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.
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.
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.
A representation of a satisfied reference.
1.3
Not Thread-safe
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.
The name of the declared reference.
This is declared in the name
attribute of the reference
element of the component description.
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.
A representation of an unsatisfied reference.
1.3
Not Thread-safe
The name of the declared reference.
This is declared in the name
attribute of the reference
element of the component description.
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.
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.
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)"
-
ExportedService
- Component Property Type for the remote service properties for an exported service. -
SatisfyingConditionTarget
- Component Property Type for theosgi.ds.satisfying.condition.target
reference property. -
ServiceDescription
- Component Property Type for theservice.description
service property. -
ServiceRanking
- Component Property Type for theservice.ranking
service property. -
ServiceVendor
- Component Property Type for theservice.vendor
service property.
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
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
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
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
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
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
Filter expression to select the component's satisfying condition.
The filter expression to select the component's satisfying condition.
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
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
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
[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
[3]Java Properties Filehttps://docs.oracle.com/javase/8/docs/api/java/util/Properties.html
[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