152 CDI Integration Specification

152.1 Introduction

Contexts and Dependency Injection ([1] CDI) is the standard dependency injection technology for Java. [2] CDI 2.0 is the current version.

The CDI specification is a composition of the following high level features:

 
  • A well-defined life cycle for stateful objects bound to life cycle contexts, where the set of contexts is extensible

  • A sophisticated, typesafe dependency injection mechanism, including the ability to select dependencies at either development or deployment time, without verbose configuration

  • Support for Java EE modularity and the Java EE component architecture - the modular structure of a Java EE application is taken into account when resolving dependencies between Java EE components

  • Integration with the Unified Expression Language (EL), allowing any contextual object to be used directly within a JSF or JSP page

  • The ability to decorate injected objects

  • The ability to associate interceptors to objects via typesafe interceptor bindings

  • An event notification model

  • A web conversation context in addition to the three standard web contexts defined by the Java Servlets specification

  • A Service Provider Interface (SPI) allowing portable extensions to integrate cleanly with the container

 
  --CDI

This specification describes how OSGi is integrated into the CDI programming model and the interaction with these features.

152.1.1 Essentials

  • Dependency Injection - Provide an advanced dependency injection framework for bundles that can create and wire objects and services together into an application.

  • Extender Model - Enable the configuration of components inside a bundle based on configuration data provided by the bundle developer. The life cycle of these components is controlled by the extender based on the extended bundle's state.

  • Unencumbered - Does not require any special bundle activator or other code to be written inside the bundle in order to have components instantiated and configured.

  • Services - Enable the usage of OSGi services as injected dependencies.

  • Configuration - Enable the usage of Configuration Admin configuration objects as injected dependencies.

  • Dependencies - Allow components to depend on configuration objects and services and to register services, with the full breadth of the OSGi capabilities.

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

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

  • Business Logic - A focus on writing business logic by using the features of CDI and reusable functionality provided by extensions.

  • Familiarity - Familiar to Java developers knowledgeable in CDI.

152.1.2 Entities

  • CDI Entities

    • CDI - Contexts and Dependency Injection 2.0.

    • Bean - A Java class that satisfies the criteria of a bean as defined in CDI and which provides contextual objects that define application state and/or logic.

    • Producer - A producer method or field acts as a source of objects to be injected. It is an alternative to beans.

    • Contextual Instance - The object instances produced by beans or producers within a given context.

    • Context - A Service Provider Interface (SPI) defining the life cycle for a set of contextual instances. The context also determines which contextual instances of beans are visible to the contextual instances of other beans.

    • Scope - A (CDI) scope identifies a particular Context implementation. All beans have a scope and are therefore bound to a particular context implementation. A scope is represented by an annotation type. Any contextual instances produced from the bean exist within a context identified by the scope.

    • Injection Point - A location in a contextual instance or producer which is the target for injection for a contextual instance.

    • Qualifier - An annotation used to define a quality used for matching. Qualifiers are applied to injection points, beans, producers (among other things). CDI finds beans matching an injection point's type then makes sure the qualifiers of the bean match all those on the injection point.

    • Stereotype - An annotation meta-annotated with javax.enterprise.inject.Stereotype used to define a recurring role by aggregating a CDI scope and various other aspects into a reusable unit.

    • Decorators and Interceptors - Actors that intercept certain method invocations of contextual instances.

    • Portable Extension - A portable extension uses the CDI SPI to provide additional and reusable functionality to a set of CDI beans.

    • CDI Container - For each CDI bundle, required portable extensions are loaded , metadata and bean classes are analyzed to create a bean injection graph. This process is encapsulated by a CDI container.

  • Entities defined by this specification

    • CDI Bundle - An OSGi bundle containing CDI beans.

    • CDI Extension Bundle - A bundle providing one or more portable extensions.

    • CDI Component Runtime (CCR) - The actor that manages the CDI containers and their life cycle and allows introspection of CDI containers.

    • Configuration Object - Configuration Admin object which implements the Configuration interface and contains configuration data.

    • Factory Configuration Object - A Configuration Object having a factory PID whose instances for which there can be 0 or N are under the control of Configuration Admin, all sharing the same factory PID.

    • Single Configuration Object - A configuration object that has no factory PID and remains singularly independent from all other configuration objects.

    • Component - A set of beans whose life cycle is derived from it's dependencies.

    • Dependency - A configuration object or service upon which beans depend. These dependencies are dynamic in that their life cycle is independently controlled by other actors within the OSGi Framework and CCR must properly accommodate for this.

    • Configuration Template - The static metadata describing a configuration object dependency.

    • Reference Template - The static metadata describing a reference dependency.

    • Component Template - The static definition of a component combining all the metadata defined by its beans, and its dependencies. The component template does not change between restarts of the CDI bundle.

    • Component Scope - A (CDI) scope defined by this specification that represents the granular life cycle associated with a set of dependencies.

    • Component Instance - A runtime instance of the component template which observes and reacts to the state of the OSGi Framework based on the metadata of the component template.

    • Container Component - A component encompassing all beans in the CDI container not in the component scope. The container component results in a single component instance.

    • Single Component - A component that encompasses beans that have the Component Scope, whose dependencies may include single configuration objects and services. A single component results in a single component instance.

    • Factory Component - A component that encompassed beans having the Component Scope, that are driven by factory configuration objects and whose dependencies may include single configuration objects and services. A factory component results in any number of component instances, one for every factory configuration object.

152.1.3 Synopsis

The CDI Extender reads CDI metadata from started CDI bundles. These metadata are in the form of XML documents, annotation types and requirements which define the set of beans available to the CDI container. Beans express dependencies on OSGi configuration objects and services and are assembled into components. The life cycle of a component is driven from the dependencies of its beans.

There are three types of components:

  • Container Component - Consists of beans not in the component scope. There is exactly one container component per CDI bundle. It's life cycle is synonymous with the CDI container. The container component must be completely satisfied before other component types can be satisfied. The container component may provide multiple services. Altering the state of the container component's static dependencies results in the entire CDI container, and all other component types being destroyed and recreated.

  • Single Component - A Single Component begins with a bean annotated by the @SingleComponent annotation and is further enhanced by other beans in it's injection graph that are component scoped. A single component may provide immediate functionality or a service resulting in an immediate instance or a single service registration. Unlike the container component, single components may be created, destroyed and react to changes in the state of it's dependencies in isolation, without affecting the entire CDI container. A single component's life cycle is driven first by the container component which must be satisfied and second by it's dependencies.

  • Factory Component - A Factory Component begins with a bean annotated by the @FactoryComponent annotation and is further enhanced by other beans in it's injection graph that are component scoped. A factory component may provide immediate functionality or a service, resulting in one immediate instance or service registration. Unlike the container component, factory components may be created, destroyed and react to changes in the state of it's dependencies in isolation, without affecting the entire CDI container. A factory component's life cycle is driven first by the container component which must be satisfied, secondly by factory configuration which result in one component instance per factory configuration object, and finally by it's dependencies.

Figure 152.1 CCR Model

CCR Model

152.2 Components

A traditional CDI application is composed of beans that have a well-defined life cycle based on the CDI scope they declare. This specification defines a component model in terms of beans and scopes as they are defined in the CDI specification in order to act as a good CDI citizen.

Components are defined by this specification to have the following characteristics:

  • Components exist within a CDI bundle.

  • Components are defined by collections of beans (referred to as component beans).

  • Components may have dependencies on configuration objects and services. These dependencies are described using annotations defined by this specification.

  • Components have properties, referred to as component properties. Some of these are defined by this specification and must be present. Others are aggregated from various configuration sources as defined in Component Properties.

  • Components have unique names within the CDI bundle.

  • Components produce one or more component instances. Component instances are the runtime representation of the component. They independently react to the state of the dependencies declared by their component beans.

152.3 Component Scope

This specification uses the facilities of CDI [8] Scopes and contexts to define a life cycle for beans specifically for supporting a relationship with OSGi dependencies.

Associated with every CDI scope is an object implementing javax.enterprise.context.spi.Context or javax.enterprise.context.spi.AlterableContext. The life cycle and visibility rules for said scope are defined by this implementation which collaborates with the CDI container to create or destroy contextual instances. Contextual instances associated with the scope exist within a context which acts as a cache, creating new or returning existing contextual instances as needed. These contexts are managed by CCR in conjunction with the CDI container.

Figure 152.2 CDI Scope Model

CDI Scope Model

The component scope is a [9] Pseudo-scope identified by the @ComponentScoped annotation. The component scope allows component instances to use component beans to create or destroy contextual instances when dependencies are satisfied or unsatisfied without interfering with the life cycle of other component instances (including the container component).

The context implementation must be registered with the CDI container using the CDI SPI. For example:

void afterBeanDiscovery(
	@Observes javax.enterprise.inject.spi.AfterBeanDiscovery abd) {

	Context ctx = ...
	abd.addContext(ctx);
}

The ComponentScoped annotation must be registered with the CDI container using the CDI SPI. For example:

void beforeBeanDiscovery(
	@Observes javax.enterprise.inject.spi.BeforeBeanDiscovery bbd) {

	bbd.addScope(ComponentScoped.class, false, false);
}

152.3.1 Contexts

The creation and destruction of the component scope's contexts must adhere to the following process:

  • The following steps are taken to create a context:

    1. the context is made active - The method javax.enterprise.context.spi.Context.isActive() must return true.

    2. contextual instances are created and injected - Contextual instances can be retrieved by calling javax.enterprise.context.spi.Context.get(...).

    3. the @Initialized event is fired - On success of step 2, the CDI event @Initialized(ComponentScoped.class) is fired synchronously. See Table 152.1.

      When the component is a single component, the event payload is the contextual instance of the bean marked @SingleComponent.

      When the component is a factory component the event payload is the contextual instance of the bean marked @FactoryComponent.

      Any qualifiers defined on the bean of the contextual instance must be attached to the event.

      On failure of step 2, errors are logged and made available in errors.

    4. the context is deactivated - The method javax.enterprise.context.spi.Context.isActive() must return false.

  • The following steps are taken to destroy a context:

    1. the context is made active - The method javax.enterprise.context.spi.Context.isActive() must return true.

    2. the @BeforeDestroy is fired - The CDI event @BeforeDestroy(ComponentScoped.class) is fired synchronously. See Table 152.1.

      When the component is a single component the event payload is the contextual instance of the bean marked @SingleComponent.

      When the component is a factory component the event payload is the contextual instance of the bean marked @FactoryComponent.

      Any qualifiers defined on the bean of the contextual instance must be attached to the event.

    3. contextual instances are destroyed - Any exceptions are logged.

    4. the context is deactivated - The method javax.enterprise.context.spi.Context.isActive() must return false.

    5. the context is destroyed

    6. the @Destroyed event is fired - The CDI event @Destroyed(ComponentScoped.class) is fired synchronously. See Table 152.1.

      When the component is a single component the event payload is the contextual instance of the bean marked @SingleComponent.

      When the component is a factory component the event payload is the contextual instance of the bean marked @FactoryComponent.

      Any qualifiers defined on the bean of the contextual instance must be attached to the event.

      Note that the object may not be usable during this event because the context under which it was created is already destroyed.

Table 152.1 Component Context Events

Event Qualifier Condition
@Initialized(ComponentScoped.class) when a context is initialized and ready for use
@BeforeDestroy(ComponentScoped.class) when a context is about to be destroyed, but before actual destruction
@Destroyed(ComponentScoped.class) after a context is destroyed

152.3.1.1 When Contexts are Created

A context is created under each of the following conditions:

  1. Immediate instance - A component instance that does not provide a service requires the immediate creation of a context.

  2. Singleton scoped service from a @SingleComponent - A single component instance that provides a singleton scoped service requires the immediate creation of a context.

    The service object is the contextual instance of the bean marked @SingleComponent obtained from the context.

  3. Singleton scoped service from a @FactoryComponent - A factory component instance that provides a singleton scoped service requires the immediate creation of a context for each factory configuration object.

    The service object is the contextual instance of the bean marked @FactoryComponent obtained from the context.

  4. Bundle scoped service - A component instance that provides a bundle scope service requires the creation of a context when the ServiceFactory.getService() method is called.

    If the component is a single component, the service object is the contextual instance of the bean marked @SingleComponent obtained from the context.

    If the component is a factory component, the service object is the contextual instance of the bean marked @FactoryComponent obtained from the context.

    The context is released and destroyed when the ServiceFactory.ungetService() method is called.

  5. Prototyped scoped service - A component instance that provides a prototype scope service requires the creation of a context when the PrototypeServiceFactory.getService() method is called.

    If the component is a single component, the service object is the contextual instance of the bean marked @SingleComponent obtained from the context.

    If the component is a factory component, the service object is the contextual instance of the bean marked @FactoryComponent obtained from the context.

    The context is released and destroyed when the PrototypeServiceFactory.ungetService() method is called.

In addition to the cases specified above, all contexts produced by an immediate component or by the service registration are released and destroyed when the component instance is no longer satisfied or when the CDI container is destroyed.

152.4 Container Component

The container component is composed of all the beans available to the CDI container which are not ComponentScoped.

The container component draws it's name from the CDI container id. By default, the CDI container id is equal to the Bundle-SymbolicName of the CDI bundle prefixed by 'osgi.cdi.'.

containerId ::= 'osgi.cdi.' bsn
bsn         ::= < Bundle-SymbolicName >

The container id can be specified using the container.id attribute of the CDI extender requirement in the bundle manifest. The value must follow the Bundle-SymbolicName syntax. For example:

Require-Capability:
	osgi.extender;
		filter:=”(&(osgi.extender=osgi.cdi)(version>=1.0)(!(version>=2.0.0)))”;
		container.id="my.id"

152.4.1 Container Component Configuration

The container component must be configurable using it's container id as a PID; referred to as the container PID.

containerPID ::= < container id >

Given a bundle with Bundle-SymbolicName equal to com.acme.bar which does not set the container.id attribute in the requirement, the container id would be:

osgi.cdi.com.acme.bar

From the requirement example above where the container id is set to my.id, the container PID would be:

my.id

The configuration object used to satisfy the container PID must be a single configuration object. However the configuration policy for this configuration object is optional and is not required to satisfy the container component.

152.4.2 Container Component Life Cycle

The container component is largely synonymous with the CDI container. When the dependencies of the container component are satisfied the CDI container completes it's initialization process and subsequently is fully functional. When the dependencies of the container component are no longer satisfied the CDI container is shutdown and all contextual instances are destroyed.

A container component with no beans would be immediately satisfied since it specifies no dependencies.

152.5 Standard Definitions

152.5.1 Annotation Inheritance

Annotations are not inherited unless meta-annotated by @java.lang.annotation.Inherited.

152.5.2 Code Examples

This specification provides several source code examples. In order to avoid repetition the following Java types are defined and re-used throughout:

interface Dog {}

interface Hound extends Dog {}

abstract class BassetHound implements Hound {}

class Spot extends BassetHound {}

class Buddy implements Hound {}

152.6 Single Component

A Single Component begins with and is rooted by a bean annotated by the @SingleComponent annotation. It is further enhanced by beans in it's injection graph that are @ComponentScoped which are discovered according to CDI's rules for [7] Typesafe Resolution starting from the @SingleComponent bean and recursing through all injection points until all injection points are resolved.

Resolution results which contain non-root beans marked with @SingleComponent or @FactoryComponent result in a definition error.

Any failed resolutions result in a definition error.

Applying any scope besides @ComponentScoped to a bean marked with @SingleComponent results in a definition error.

Any @ComponentProperties or @Reference injection point that is resolved by beans which are not provided by CCR results in a definition error.

A single component has an implicit dependency on the container component. Therefore it may never be satisfied until the container component is satisfied.

152.6.1 Single Component Naming

The @SingleComponent annotation is a stereotype which carries the @javax.inject.Named meta-annotation. This indicates that the default component name is:

 

the unqualified class name of the bean class, after converting the first character to lower case

 
  --CDI

For example:

// component.name = fido
@SingleComponent
class Fido {}

However, the name may be specified by adding @javax.inject.Named directly to the bean and specifying a value whose syntax follows cname defined by the [11] General Syntax Definitions.

// component.name = Champ
@SingleComponent
@Named("Champ")
class Fido {}

152.6.2 Single Component Configuration

By default a single component must be configurable by using it's component name, prefixed by the container PID and a period (.), as a configuration PID. This component PID will be represented throughout the remained of the specification by the symbol Φ (capital Phi).

Φ           ::= containerPID '.' compName
containerPID ::= < container PID >
compName     ::= < component name >

A single component may change or add additional PIDs on which it depends. When multiple PIDs are referenced the order is relevant and affects the aggregation of the configuration objects into a flattened dictionary of component properties. Later PIDs take precedence over earlier PIDs. Also, it must be possible to reposition the component PID within the order. The PID annotation is used to control both referenced PIDs and their order.

The following is an example of a component that is configurable by it's component PID:

// component pids = [Φ]
@SingleComponent
class Fido {}

An example of a component replacing it's component PID with a specific PID:

// component pids = [com.acme.foo]
@SingleComponent
@PID("com.acme.foo")
class Fido {}

An example of multiple PIDs:

// component pids = [com.acme.foo, com.gamma.bar]
@SingleComponent
@PID("com.acme.foo")
@PID("com.gamma.bar")
class Fido {}

See Component Properties for how multiple component PIDs are merged into component properties.

Using @PID without arguments refers to the component PID:

// component pids = [Φ]
@SingleComponent
@PID
class Fido {}

This allows the component PID to be included anywhere in the order:

// component pids = [com.acme.foo, Φ, com.gamma.bar]
@SingleComponent
@PID("com.acme.foo")
@PID
@PID("com.gamma.bar")
class Fido {}

Each @PID annotation may specify a policy for the configuration object. The property policy is used to specify the value. The possible values are:

  • OPTIONAL - A configuration object is not required. This is the default policy.

  • REQUIRED - A configuration object is required.

// component pids = [com.acme.foo, Φ, com.gamma.bar]
@SingleComponent
@PID(value = "com.acme.foo", policy = Policy.REQUIRED)
@PID
@PID("com.gamma.bar")
class Fido {}

It is a definition error to refer to the same PID more than once.

The configuration objects used to satisfy the single component's referenced PIDs must be single configuration objects.

152.7 Factory Component

A Factory Component begins with and is rooted by a bean annotated by the @FactoryComponent annotation. It is further enhanced by beans in it's injection graph that are @ComponentScoped which are discovered according to CDI's rules for [7] Typesafe Resolution starting from the @FactoryComponent bean and recursing through all injection points until all injection points are resolved.

The @FactoryComponent annotation indicates that the component is bound to the life cycle of factory configuration objects associated with the factory PID specified in it's value property (or it's default component factory PID). Each factory configuration object associated with this factory PID results in a new component instance. The component properties of the component instance are supplemented by the properties of the factory configuration object.

Resolution results which contain a non-root bean marked with @SingleComponent or @FactoryComponent result in a definition error.

Any failed resolutions result in a definition error.

Applying any scope besides @ComponentScoped to a bean marked with @FactoryComponent results in a definition error.

Any @ComponentProperties or @Reference injection point that is resolved by beans which are not provided by CCR results in a definition error.

A factory component has an implicit dependency on the container component. Therefore it may never be satisfied until the container component is satisfied.

152.7.1 Factory Component Naming

The @FactoryComponent annotation is a stereotype which carries the @javax.inject.Named meta-annotation. This indicates that the default component name is:

 

the unqualified class name of the bean class, after converting the first character to lower case

 
  --CDI

For example:

// component.name = fido
@FactoryComponent
class Fido {}

However, the name may be specified by adding @javax.inject.Named directly to the bean and specifying a value whose syntax follows cname defined by the [11] General Syntax Definitions.

// component.name = Champ
@FactoryComponent
@Named("Champ")
class Fido {}

152.7.2 Factory Component Configuration

By default a factory component must be configurable by using it's component name, prefixed by the container PID and a period (.), as a factory PID. This component factory PID will be represented throughout the remained of the specification by the symbol Σ (capital Sigma).

Σ            ::= containerPID '.' compName
containerPID ::= < container PID >
compName     ::= < component name >

An example of a factory component that is configurable by it's component factory PID:

// component pids = [Σ]
@FactoryComponent
class Fido {}

A factory component may specify a factory PID using it's value property. The value must conform to the syntax defined for the Bundle-SymbolicName header.

An example of a factory component specifying a factory PID:

// component pids = [com.acme.foo-####]
@FactoryComponent("com.acme.foo")
class Fido {}

A factory component may change or add additional PIDs on which it depends. When multiple PIDs are referenced the order is relevant and affects the aggregation of the configuration objects into a flattened dictionary of component properties. Later PIDs take precedence over earlier PIDs. The PID annotation is used to control both referenced PIDs and their order.

An example of multiple PIDs:

// component pids = [com.gamma.bar, com.acme.foo-####]
@FactoryComponent("com.acme.foo")
@PID("com.gamma.bar")
class Fido {}

Each @PID annotation may specify a policy for the configuration dependency. The property policy is used to specify the value. The possible values are:

  • OPTIONAL - A configuration object is not required. This is the default policy.

  • REQUIRED - A configuration object is required.

// component pids [com.acme.foo, com.gamma.bar, Σ]
@FactoryComponent
@PID(value = "com.acme.foo", policy = Policy.REQUIRED)
@PID("com.gamma.bar")
class Fido {}

See Component Properties for how multiple component PIDs are merged into component properties.

The component factory PID always reserves the highest precedence among specified PIDs and is positioned last in PID ordering for the purpose of aggregation

A factory component can only reference a single factory PID.

Notwithstanding the factory PID, it is a definition error to refer to the same PID more than once.

The configuration object used to satisfy the factory component's component factory PID must be a factory configuration object.

Configuration objects used to satisfy the PIDs referred to by the @PID annotations must be single configuration objects.

152.8 Component Properties

Each component instance is associated with a set of component properties. Component properties are specified in the following configuration sources (in order of precedence, where the properties provided by later lines overwrite those of earlier lines):

  1. Properties specified as Bean Property Types on the bean annotated with @SingleComponent or @FactoryComponent must be treated according to Bean Property Types.

  2. Properties provided by single configuration objects whose PIDs are matched to and are processed in the order they are specified by the component.

  3. Properties provided by a factory configuration object whose PID matches to the factory PID specified by the factory component.

The precedence behavior allows certain default values to be specified in component metadata while allowing properties to be replaced and extended by a configuration object.

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, CCR 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 refers to multiple PIDs, then the order of the service.pid property values collected from the corresponding configuration objects must match the order in which the PIDs are specified by the component. The values of the service.pid component property are the values as they come from the configuration sources and may container more values than those referred to by the component.

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

  • component.name - The component name. The syntax for the component.name follows cname defined by the [11] General Syntax Definitions.

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

152.8.1 Reference Properties

This specification defines some component properties which are associated with a specific reference. 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.

152.8.1.1 Target Property

The target property is a reference property which aids in the selection of target services for the reference. See Reference Injection Points. The name of a target property is the name of a reference appended with .target.

target  ::= refName '.target'
refName ::= < reference name >

For example, the target property for a reference with the name http

@Inject
@Reference
Http http;

would have the name http.target. The value of a target property is a filter String used to select target services for the reference.

http.target=(context.name=foo)

A default target property value can also be set by the @Reference.target property.

The target property value must be a valid filter String according to [12] Filter Syntax. Invalid filters result in unmatchable reference filters.

CCR must support the target property for all references.

152.8.1.2 Minimum Cardinality Property

The initial minimum cardinality of a reference is specified by the optionality of the reference. The minimum cardinality of a reference cannot exceed the multiplicity: a scalar reference has a multiplicity of 1 and a java.util.List or java.util.Collection reference has a multiplicity of n.

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. A 0..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. A mandatory reference cannot be reduced to optional through this property. That is, a 1..1 cardinality can not be lowered to a 0..1 cardinality because the component was written to expect at least one bound service.

The name of a minimum cardinality property is the name of a reference appended with .cardinality.minimum.


minimumCardinality ::= refName '.cardinality.minimum'
refName            ::= < reference name >

For example, the minimum cardinality property for a reference with the name http

@Inject
@Reference
Http http;

would have the name http.cardinality.minimum.

http.cardinality.minimum=3

The value of a minimum cardinality property must be a positive integer or a value that can be coerced into a positive integer using the conversions defined by the Converter Specification. 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 and a warning message logged.

Attempts to reduce the initial minimum cardinality will result in a warning message to be logged and the value to be otherwise ignored.

CCR must support the minimum cardinality property for all references.

152.9 Bean Property Types

Component properties can be defined and accessed through a user defined annotation type, called a bean property type, containing the property names, property types and default values. A bean property type allows properties to be defined and accessed in a type safe manner. Bean Property Types must be annotated with the BeanPropertyType meta-annotation.

The following example shows the definition of a bean property type called Props 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.

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

Bean Property Types can be used in several ways:

  • Bean Property Types can be used along side the SingleComponent or FactoryComponent annotations to provide component properties.

  • Bean Property Types can be used on ApplicationScoped or Dependent scoped beans, where the Service annotation is applied to provide service properties.

  • Bean Property Types can be used on fields and methods annotated with @Produces, where the Service annotation is applied, to provide service properties.

  • Bean Property Types can be used on injection points where the Reference annotation is applied, to provide target filter properties. Target filter properties can only provide AND filters.

  • Bean Property Types can be used on injection points as the injection point type where the ComponentProperties annotation is applied to provide type safe coercion of component properties.

Each use defines property names, types and values.

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

@SingleComponent
@Props(names="myapp")
public class MyBean {
	@Inject
	void activate(Props props) {
		if (props.enabled()) {
			// do something
		}
		for (String name : props.names()) {
			// do something with each name
		}
	}
}

Bean 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 Bean 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 bean classes.

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

152.9.1 Bean Property Type Mapping

Each method of a bean 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 bean property type declares a PREFIX_ field whose value is a compile-time constant String, then the property name is prefixed with the value of the PREFIX_ field.

Table 152.2 contains some name mapping examples.

Table 152.2 Bean Property Type Name Mapping Examples

Bean 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 bean property type is a single-element annotation, see 9.7.3 in [16] The Java Language Specification, Java SE 8 Edition, then the property name for the value method is derived from the name of the bean property type rather than the name of the method.

In this case, the simple name of the bean property type, that is, the name of the class without any package name or outer class name, if the bean 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 bean property type declares a PREFIX_ field whose value is a compile-time constant String, then the property name is prefixed with the value of the PREFIX_ field.

Table 152.3 contains some mapping examples for the value method.

Table 152.3 Single-Element Annotation Mapping Examples for value Method

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

If the bean property type is a marker annotation, see 9.7.2 in [16] The Java Language Specification, Java SE 8 Edition, then the property name is derived from the name of the bean 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 beans to set a component property to the value Boolean.TRUE. However, since marker annotations have no methods, they are of no use as injection point types.

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.

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.

152.9.2 Coercing Bean Property Type Values

When a bean property type is used as an injection point type alone with @ComponentProperties, CCR must create a contextual instance that implements the bean property type and maps the methods of the bean property type to component properties. The name of the method is converted to the property name as described in Bean Property Type Mapping. The property value may need to be coerced to the type of the method. In Table 152.4, 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 Bean Property Exception when the bean 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 Bean Property Exception and thrown when the bean property type method is called.

Table 152.4 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 bean property type methods are ignored. If there is no corresponding component property for a bean property type method, the bean 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 BeanPropertyException for annotation method types.

152.9.3 Standard Bean Property Types

Bean Property Types for standard service properties are specified in the org.osgi.service.cdi.propertytypes package.

The ServiceDescription bean property type can be used to add the service.description component property, service property or target filter. The ServiceRanking bean property type can be used to add the service.ranking component property, service property or target filter. The ServiceVendor bean property type can be used to add the service.vendor component property, service property or target filter. For example, using these Bean Property Types as annotations:

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

will result in the following component properties:

service.description=My Acme Service implementation # String
service.ranking=100 # Integer
service.vendor=My Corp # String

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

152.10 Providing Services

A key aspect of working with OSGi is the ability to provide services. Services are published to the service registry specifying service types. The @Service annotation provides this capability to CCR and serves a dual role; the first of which is indicating that a bean publishes a service, the second indicating the service types. @Service can be applied in any one of the following ways:

152.10.1 @Service applied to bean class

Applying the @Service annotation to the bean class indicates the set of service types will be one of (in order of precedence):

  1. the specified type(s) - When providing a specified value, these are the types under which the service is published.

    // service types = [BassetHound, Dog]
    @Service({BassetHound.class, Dog.class})
    class Spot {}
  2. directly implemented interfaces - These are the interfaces for which the bean class directly specifies an implements clause.

    // service types = [Hound]
    @Service
    class Fido implements Hound {}
  3. bean class - The class of the bean itself is the type under which the service is published.

    // service types = [Fido]
    @Service
    class Fido

The @Service annotation is never inherited. CCR ignores instances of the annotation on super classes, interfaces or super interfaces for this purpose.

152.10.2 @Service applied to type use

A convenient readability optimization is to apply the @Service annotation on type_use. This is to say that it may be applied to extends and/or implements clauses. For example:

// service types = [BassetHound]
class Fido extends @Service BassetHound {}

Or:

// service types = [Hound]
class Fido implements @Service Hound {}

The two approaches can be combined. @Service annotations are collected so that the service is published with all collected types:

// service types = [BassetHound, Hound]
class Fido extends @Service BassetHound implements @Service Hound {}

In this scenario, any use of the @Service.value property will result in a definition error.

Applying @Service to both bean class, and type use will result in a definition error.

152.10.3 @Service applied to Producers

Applying the @Service annotation to producer methods or fields indicates the set of service types as described in the following table (earlier rows take precedence over later rows).

Table 152.5 @Service applied to Producers

Case Description

the type(s) specified by @Service.value

When providing a specified @Service.value, these are the types under which the service is published.

// service types = [BassetHound, Dog]
@Produces
@Service({BassetHound.class, Dog.class})
Spot getSpot() {
	return new Spot();
}

the returned interface

In the case of a producer method, if the return type is an interface, this type is used as the service type.

// service types = [Dog]
@Produces
@Service
Dog getDog() {
	return new Spot();
}

all directly implemented interfaces of returned type

In the case of a producer method, if the return type is a concrete type, use any interfaces directly implemented by the concrete type.

// service types = [Hound]
@Produces
@Service
Buddy getBuddy() {
	return new Buddy();
}

the return type

In the case of a producer method, if the return type is a concrete type which does not directly implement any interfaces, use the concrete type.

class Fido {}

// service types = [Fido]
@Produces
@Service
Fido getFido() {
	return new Fido();
}

the field interface

In the case of a producer field, if the field type is an interface this type is used as the service type.

// service types = [Dog]
@Produces
@Service
Dog dog = new Spot();

all directly implemented interfaces of the field type

In the case of a producer field, if the field type is a concrete type use any interfaces directly implemented by the concrete type.

// service types = [Hound]
@Produces
@Service
Buddy buddy = new Buddy();

the field type

In the case of a producer field if the field type is a concrete type which does not directly implement any interfaces use the concrete type.

class Fido {}

// service types = [Fido]
@Produces
@Service
Fido fido = new Fido();

152.10.4 @Service Type Restrictions

Regardless of the source, no service type may be a generic type. A generic type found in the set of service types will result in a definition error.

Service types must be a subset of bean types, including types restricted by the use of the @javax.enterprise.inject.Typed annotation. This restriction is required to support CDI features like Decorators and Interceptors.

Using the @Service annotation on injection points will result in a definition error.

152.10.5 Service Properties

The main source of service properties is Component Properties.

When CCR registers a service on behalf of a component instance, CCR 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.

152.10.5.1 Container component service properties

In addition to component properties, services provided by the container component obtain additional service properties from Bean Property Types on the bean or producer providing the service. See Bean Property Types.

152.10.6 Service Scope

Service scope represents the scope of the registered service object. There are three scopes supported by the OSGi Framework. Each can be represented in CCR.

  • Bundle scope - In order to specify a bundle scoped service, the @ServiceInstance annotation is specified on the bean class, producer method or producer field with the value BUNDLE.

    @Service
    @ServiceInstance(ServiceScope.BUNDLE)
    class Fido implements Hound {}
  • Prototype scope - In order to specify a prototype scoped service, the @ServiceInstance annotation is specified on the bean class, producer method or producer field with the value PROTOTYPE. The service object is the contextual instance created by the producer or bean.

    @Service
    @ServiceInstance(ServiceScope.PROTOTYPE)
    class Fido implements Hound {}
  • Singleton scope - Unless otherwise specified, services are singleton scoped but the scope can be explicitly expressed if the @ServiceInstance annotation is specified on the bean class, producer method or producer field with the value SINGLETON. The service object is the contextual instance created by the producer or bean.

    @Service
    @ServiceInstance(ServiceScope.SINGLETON) // equal to omitting the annotation
    class Fido implements Hound {}

152.10.7 Container Component Services

Beans, producer methods and producer fields that are @ApplicationScoped result in contextual instances that are shared throughout the CDI container. Therefore they can only provide singleton scoped services. Each such case results in a single service registration. The service object is the contextual instance created by the producer or bean. However, @ApplicationScoped beans can implement org.osgi.framework.ServiceFactory or org.osgi.framework.PrototypeServiceFactory in order to provide bundle or prototype scoped service objects.

Beans, producer methods and producer fields that are @Dependent result in contextual instances which are never shared in that a new contextual instance is created for each caller. Therefore they can provide services of all scopes as outlined in Service Scope. The service object is a contextual instance created by the producer or bean on each request for a service object.

The use of @ServiceInstance on @ApplicationScoped beans will result in a definition error.

152.10.8 Single Component Services

Single components can only apply the @Service annotation to beans marked with @SingleComponent.

A single component providing a service results in a single service registration.

Service objects provided by the service registration are defined by the creation of contexts. In all cases, the service object provided is the contextual instance of the bean marked @SingleComponent obtained from the context.

152.10.9 Factory Component Services

Factory components can only apply the @Service annotation to beans marked with @FactoryComponent.

A factory component providing a service results in one service registration for every factory configuration object associated with the factory PID of the component.

Service objects provided by the service registration are defined by the creation of contexts. In all cases, the service object provided is the contextual instance of the bean marked @FactoryComponent obtained from the context.

152.11 Component Property Injection Points

A bean specifies injection of component properties using the @ComponentProperties annotation at an injection point.

The type typically associated with component properties is java.util.Map<String, Object>:

@Inject
@ComponentProperties
Map<String, Object> componentProperties;

However, component properties can be automatically converted to any type compatible with the conversions defined by the Converter Specification.

Given the following configuration properties:

pool.name (String)
min.threads (int)
max.threads (int)
keep.alive.timeout (long)

The following example demonstrates conversion of component properties into a type safe object with defaults.

public static @interface PoolConfig {
	String pool_name();
	int min_threads() default 2;
	int max_threads() default 10;
	long keep_alive_timeout() default 500;
}

@Inject
@ComponentProperties
PoolConfig poolConfig;

Using @Reference in conjunction with @ComponentProperties will result in a definition error.

152.11.1 Coordinator Support

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

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

152.12 Reference Injection Points

Any injection point annotated with @Reference declares a service dependency.

152.12.1 Reference injection point types

Injection points specifying @Reference are limited to one of the following injection point types as representations of the dependent service(s). Given that type S is a type under which a service is published, the following injection point types are supported:

Table 152.6 Reference injection point types

Injection Point Type Description
S
// S = Dog
@Inject
@Reference
Dog dog;
org.osgi.framework.ServiceReference<S>
// S = Dog
@Inject
@Reference
ServiceReference<Dog> dog;
java.util.Map<String, ? | Object>

In this case the @Reference annotation must specify service type S using it's value property.

// S = Dog
@Inject
@Reference(Dog.class)
Map<String, Object> dogProperties;

Failure to specify the type in this scenario results in a definition error.

java.util.Map.Entry<Map<String, ? | Object>, S>

Represents a tuple containing the map of service properties as the key and the service instance as the value.

// S = Dog
@Inject
@Reference
Map.Entry<Map<String, ?>, Dog> dog;
BeanServiceObjects<S>
// S = Dog
@Inject
@Reference
BeanServiceObjects<Dog> dogs;

S must be a concrete service type. The OSGi service registry does not support generics, therefore S cannot specify a generic type.

A definition error will result if any other types are used with injection points marked @Reference unless otherwise specified by this specification.

152.12.2 Reference Service scope

For a bound service, CCR 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, CCR 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 where the PrototypeRequired annotation was specified, 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 @PrototypeRequired effectively adds service.scope=prototype to the target property of the reference. A service that does not use prototype service scope cannot be used as a bound service for a reference with @PrototypeRequired since the service cannot provide a distinct service object for each component instance.

@Inject
@PrototypeRequired
@Reference
Hound hound;

152.12.3 Bean Service Objects

A Bean Service Objects for the bound service, 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.

@Inject
@PrototypeRequired
@Reference
BeanServiceObjects<Hound> hounds;

The @PrototypeRequired annotation is optional. See Service Scope.

152.12.4 Reference Greediness

References are greedy by default which means that higher ranking matches are immediately bound. Use the @Reluctant annotation to indicate that higher ranking matches should not bind once the reference has been resolved. Note that in the case of static references the component will be destroyed and recreated in order to immediately apply the better match. In the case of the container component, this will result in the entire CDI container being destroyed and recreated.

A static, greedy reference:

@Inject
@Reference
Hound hound;

A static, reluctant reference:

@Inject
@Reluctant
@Reference
Hound hound;

152.12.5 Service Type

As demonstrated earlier, it's possible to specify the service type of the reference by using @Reference.value() property. This supports use cases like java.util.Map<String, ?> where the service type cannot be determined.

@Inject
@Reference(Hound.class)
Map<String, Object> properties;

This makes it possible to target a more specific service type. A reference injection point whose type is Dog may target a service of type BassetHound:

@Inject
@Reference(BassetHound.class)
Dog dog;

The injection point type must be compatible with the service type. Otherwise a definition error will result.

152.12.6 Any Service Type

A special exception to the service type rules is defined when the special marker type Reference.Any is set as @Reference.value. This allows for any service to match the reference. However, the following criteria must be satisfied:

  1. @Reference.value must specify the single value Reference.Any.class

  2. @Reference.target must specify a valid, non-empty filter value

  3. The injection point service type must be java.lang.Object. For example:

    @Inject
    @Reference(value = Reference.Any.class, target = "(foo=bar)")
    Optional<Object> match;

    or

    @Inject
    @Reference(value = Reference.Any.class, target = "(foo=bar)")
    List<Object> matches;

    Note that there may be performance impacts resulting from matching too broad a set of services. By definition the above list example with a target filter equal to (service.id=*) is perfectly valid but will match all services in the registry which will likely neither be very useful nor performant.

152.12.7 Target Filter

Target services for a reference are constrained by the reference's service type and the target property. A default target filter can be applied by specifying @Reference.target() property.

For example, a component wants to track all Dog services that have a service property service.vendor whose value is equal to Acme, Ltd.:

@Inject
@Reference(target = "(service.vendor=Acme, Ltd.)")
Collection<Dog> dogs;

152.12.7.1 Bean Property Types as target filters

Annotations meta-annotated with BeanPropertyType appearing on an injection point in conjunction with the @Reference annotation will further enhance the target filter as described by the rules for converting Bean Property Types to a map of properties assembled into a filter String according to the following steps:

  1. any key=array pairs are flattened into many key=scalar pairs, one pair for each array value

  2. format every key=scalar pair using the production

    pair       ::= '(' pairKey '=' pairScalar ')'
    pairKey    ::= < key >
    pairScalar ::= < scalar >

    If scalar must contain one of the characters reverse solidus ('\' \u005C), asterisk ('*' \u002A), parentheses open ('(' \u0028) or parentheses close (')' \u0029), then these characters must be preceded with the reverse solidus ('\' \u005C) character. Spaces are significant in scalar. Space characters are defined by Character.isWhiteSpace()

  3. concatenate all results of step 2. into a single String

  4. append the value of @Reference.target() to the result of step 3.

  5. format the result of step 4. using the production

    target ::= '(' '&' step4 ')'
    step4  ::= < result of step 4. >

Given the following example:


enum Tricks {
	SIT, STAND, SHAKE_PAW, TREAT_ON_NOSE
}
@Repeatable(...)
@BeanPropertyType
@interface Trick {
	Tricks value();
}

@Inject
@Reference(target = "(service.vendor=Acme Kennels, Ltd.)")
@Trick(SIT)
@Trick(TREAT_ON_NOSE)
Dog dog;

The target filter will be:

(&(trick=sit)(trick=treat_on_nose)(service.vendor=Acme Kennels, Ltd.))

152.12.8 Reference Names

The @javax.inject.Named annotation may be used to specify a name to serve as the base of the component properties used to configure the reference. If not specified the name of the reference will be derived from the fully qualified class name of the class defining the reference injection point and the reference injection point.

The production for generated names is:

name   ::= prefix '.' suffix
prefix ::= named | qname
named  ::= < @Named.value >
suffix ::= field | ctor | method
field  ::= < name of field >
ctor   ::= 'new' pIndex
method ::= mName pIndex
mName  ::= < method name >
pIndex ::= < index of @Reference parameter >

It is a definition error to have two references with the same name.

It is a definition error to specify the @javax.inject.Named annotation with no value.

In the following example the reference name is example.Fido.mate and the target and minimum cardinality properties of the reference will be example.Fido.mate.target and example.Fido.mate.cardinality.minimum respectively:

package example;

@SingleComponent
class Fido {
	@Inject
	@Reference
	Dog mate;
}

In the following example the reference name is foo and the target and minimum cardinality properties of the reference will be foo.target and foo.cardinality.minimum respectively:

package example;

@SingleComponent
class Fido {
	@Inject
	@Named("foo")
	@Reference
	Dog mate;
}

152.12.9 Static References

Static references are the most common form of reference injection point. Static means that their values do not change during the lifetime of the component instance which means that in order to change the service bound to the reference injection point, the entire component instance must be destroyed and recreated.

The following are more examples of static reference injection points:

@Inject
@Reference
Dog dog;

@Inject
@Reference(BassetHound.class)
Map<String, Object> props;

@Inject
void setHounds(@Reference BeanServiceObjects<Hound> hounds) {...}

@Inject
@Reference
ServiceReference<Spot> spot;

Static reference injection points are mandatory by default. They require a number of services equal to or greater than their minimum cardinality to be available in order for the component instance to resolve.

152.12.10 Static Optional References

Optional reference injection points allow a component instance to become resolved when fewer matching services are found than required by the reference's minimum cardinality. The injection point type must be java.util.Optional<R> where R is one of the supported reference injection point types.

The following are examples of static optional references:

@Inject
@Reference
Optional<Dog> dog;

@Inject
@Reference(BassetHound.class)
Optional<Map<String, Object>> props;

@Inject
void setHounds(@Reference Optional<BeanServiceObjects<Hound>> hounds) {...}

@Inject
@Reference
Optional<ServiceReference<Spot>> spot;

As with other static references, static means that their values do not change during the lifetime of the component instance which means that in order to change the service bound to the reference injection point, the entire component instance must be destroyed and recreated.

152.12.11 Static Multi-cardinality References

Multi-cardinality references are specified using an injection point type of java.util.Collection<R>, or java.util.List<R> where R is one of the supported reference injection point types. Repeating the static examples as multi-cardinality references, we get:

@Inject
@Reference
List<Dog> dogs;

@Inject
@Reference(BassetHound.class)
Collection<Map<String, Object>> props;

@Inject
void setHounds(@Reference List<BeanServiceObjects<Hound>> hounds) {...}

@Inject
@Reference
Collection<ServiceReference<Spot>> spots;

Multi-cardinality references are naturally optional since the default value of the minimum cardinality property is 0. See Minimum Cardinality Property.

As with other static references, static means that their values do not change during the lifetime of the component instance which means that in order to change the services bound to the reference injection point, the entire component instance must be destroyed and recreated.

152.12.12 Default Minimum Cardinality

As stated in Minimum Cardinality Property every reference has a configurable reference property name.cardinality.minimum. However, there are cases where it is appropriate to specify a non-zero default minimum cardinality. The MinimumCardinality annotation provides this functionality.

The following is an example of setting the minimum cardinality:

@Inject
@MinimumCardinality(3)
@Reference
List<Dog> guards;

The value must be a positive integer.

Specifying this annotation on a unary reference results in a definition error.

152.12.13 Dynamic References

Dynamic reference injection points are specified using an injection point type of javax.inject.Provider<R> where R is one of the supported reference injection point types, java.util.Optional<R>, java.util.Collection<R>, or java.util.List<R>.

The following are examples of dynamic references:

@Inject
@Reference
Provider<Dog> dog;

@Inject
@Reference(BassetHound.class)
Provider<Collection<Map<String, Object>>> props;

@Inject
void setHounds(
		@Reference
		Provider<List<BeanServiceObjects<Hound>>> hounds
	) {...}

@Inject
@Reference
Provider<Optional<ServiceReference<Spot>>> spots;

The evaluation of javax.inject.Provider.get() is performed such that each invocation may produce a different result except for returning null.

Specifying the @MinimumCardinality annotation with a non-zero value on a dynamic, multi-cardinality reference results in the component not being resolved until the number of matching services becomes equal to or greater than the specified minimum cardinality.

152.13 Interacting with Service Events

It is often necessary to observe the addition, modification and removal of services from the service registry. This specification provides 3 special bean types, referred to as binder types, which make it possible to bind methods to coordinate across the service events of set of services. The type argument S indicates the service type expected unless further reduced as described by Service Type. Bean Property Types may also be used to expand the target filter as defined in Bean Property Types as target filters.

  • BindService<S> - The BindService bean allows for coordination of service events when the service instance is required.

  • BindBeanServiceObjects<S> - The BindBeanServiceObjects bean allows for coordination of service events when bean service objects are required.

  • BindServiceReference<S> - The BindServiceReference bean allows for coordination of service events when the service reference is required.

These bean types declare a builder style interface for binding the necessary methods to coordinate the events. The following example binds service event methods over the set of services whose type is Dog and having the service property service.vendor=Acme Inc.:

@Inject
@ServiceVendor("Acme Inc.")
void bindDogs(BindService<Dog> binder) {
	binder.
		adding(this::adding).
		modified(this::modified).
		removed(this::removed).
		bind();
}

void adding(Dog dog, Map<String,Object> properties) {...}
void modified(Dog dog, Map<String,Object> properties) {...}
void removed(Dog dog, Map<String,Object> properties) {...}

The terminal bind() method must be called to inform CCR that the bind process is complete. Binding a subset of methods is allowed. Only the last bind method specified for any given service event will be used. For example, given the following invocation:

@Inject
void bindDogs(BindService<Dog> binder) {
	binder.
		adding(this::addingA).
		adding(this::addingB).
		bind();
}

only the method addingB will be used.

An example of a binder type injected into a field:

@Inject
void bindDogs(BindBeanServiceObjects<Dog> binder) {
	binder.
		adding(this::adding).
		removed(this::removed).
		bind();
}

void adding(BeanServiceObjects<Dog> dogs) {...}
void removed(BeanServiceObjects<Dog> dogs) {...}

Binder objects are @Dependent objects and are not thread safe. They are intended to be used during the creation phase of component beans before the end of the [10] @PostConstruct method. Executing any binder object method after this time will result in unspecified behavior.

152.14 CDI Component Runtime

CDI Component Runtime (CCR) is the actor that manages the CDI containers and their life cycle and allows for their introspection.

152.14.1 Relationship to the OSGi Framework

CCR must have access to the Bundle Context of any CDI bundle. CCR needs access to the Bundle Context for the following reasons:

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

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

  • To interact with the Log Service on behalf of a CDI bundle.

  • To make the Bundle Context available for injection in the CDI bundle's beans.

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

152.14.2 Injecting the Bundle Context

The Bundle Context of the CDI bundle can be injected. The injection point must be of type org.osgi.framework.BundleContext and must not specify any qualifiers.

@Inject
BundleContext bundleContext;

152.14.3 Starting and Stopping CCR

When CCR is implemented as a bundle, any containers activated by CCR must be deactivated when the CCR bundle is stopped. When the CCR bundle is started, it must process the CDI metadata declared in CDI bundles. This includes bundles which are started and are awaiting lazy activation.

152.14.4 Logging Messages

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

152.14.5 Bundle Activator Interaction

A CDI bundle may also declare a Bundle Activator. Such a bundle may also be marked for lazy activation. Since CDI containers are activated by CCR and Bundle Activators are called by the OSGi Framework, a bundle using both a CDI container and a Bundle Activator must take care. The Bundle Activator's start method must not rely upon CCR having activated the bundle's CDI container. However, the CDI container 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 CDI container being activated.

152.14.6 Introspection

CCR provides an introspection API for examining the runtime state of the CDI bundles processed by CCR. CCR must register a CDIComponentRuntime service upon startup. The CDI Component Runtime service provides methods to inspect CDI containers. The service uses Data Transfer Objects (DTO) as arguments and return values. The rules for Data Transfer Objects are specified in OSGi Core Release 8.

The CDI Component Runtime service provides the following methods.

  • getContainerDTOs(Bundle...) - For each specified bundle, if the bundle is active and processed by CCR, and the bundle is a valid CDI bundle, the returned collection will contain a ContainerDTO describing the CDI container.

  • getContainerTemplateDTO(Bundle) - If the specified bundle is active and processed by CCR, and the bundle is a valid CDI bundle, the method will return a ContainerTemplateDTO describing the template metadata of the CDI container.

The runtime state of the containers 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 CDI Component Runtime service.

Figure 152.3 CDI Component Runtime DTOs

CDI Component Runtime DTOs

The ContainerDTO specifies a changeCount field of type long. Whenever the DTOs bellow the ContainerDTO change, CCR will increment the ContainerDTO's changeCount. Whenever any ContainerDTO changes, CCR will update the service.changecount service property of the CDIComponentRuntime service. CCR may use a single update to the service.changecount property to reflect updates in multiple ContainerDTOs. See org.osgi.framework.Constants.SERVICE_CHANGECOUNT in OSGi Core Release 8.

152.14.7 Logger Support

CCR provides special support for logging via the Log Service specification. CCR must provide @Dependent objects of type org.osgi.service.log.Logger and org.osgi.service.log.FormatterLogger.

To obtain the Logger object for injection, CCR 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 injection point's declaring class as the second argument, and the type of the injection point; org.osgi.service.log.Logger or org.osgi.service.log.FormatterLogger, as the third argument. The typical usage is:

@Inject
Logger logger;

@PostConstruct
void init() {
	logger.debug("Initialized");
}

Another example using method injection along with component properties (coerced to Config):

public static @interface Config {
	String component_name();
}

@Inject
void setup(@ComponentProperties Config config, Logger logger) {
	logger.trace(“Activating component {}”, config.component_name());
}

152.14.8 Disabling Components

All components in a CDI bundle are enabled by default. However, any component can be disabled through configuration using the single configuration object associated with the container PID by defining a property using the component name suffixed with .enabled. The value's type is boolean.

enabled  ::= compName '.enabled'
compName ::= < component name >

The following is an example disabling a component whose name is foo:

foo.enabled=false

The container component can be disabled using it's component name, which is the container id. As a result of disabling the container component, all components in the CDI bundle are also disabled.

152.14.9 Container Component and Service Cycles

There is no special support to allow service cycles within the container component. CDI provides existing mechanisms for wiring and collaborating within the CDI container. However, if an container component defines a dynamic, optional reference, then a service subsequently provided by the container component may satisfy the reference at some point when the container component is satisfied. However, if the reference is static and mandatory and the only potentially matching service is one provided by the container component itself, then the container component would wait forever for a service that will never arrive. This is simple design error. The information about unsatisfied references is available from the CDIComponentRuntime service.

152.15 Capabilities

CCR must provide the following capabilities.

A capability in the osgi.extender namespace declaring an extender with the name osgi.cdi. In addition to the specification packages, this capability must declare a uses constraint for the javax.inject package. For example:

Provide-Capability:
	osgi.extender;
		osgi.extender="osgi.cdi";
		version:Version="1.0";
		uses:="javax.inject, org.osgi.service.cdi, org.osgi.service.cdi.annotations,
			org.osgi.service.cdi.reference, org.osgi.service.cdi.runtime,
			org.osgi.service.cdi.runtime.dto,
			org.osgi.service.cdi.runtime.dto.template"

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

A CDI bundle must require the osgi.extender capability from CCR. This requirement will wire the bundle to the CCR implementation and ensure that CCR is using the same org.osgi.service.cdi.* packages as the bundle if the bundle uses those packages.

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

CCR must only process a CDI bundle if the bundle's wiring has a required wire for at least one osgi.extender capability with the name osgi.cdi and the first of these required wires is wired to CCR.

When using the annotations Bean or Beans, the above requirement is automatically added to the manifest when the code is processed by a supporting build tool capable of interpreting Bundle Annotations defined in OSGi Core Release 8.

The requirement may be specified directly on any class or package in the CDI bundle by using the RequireCDIExtender annotation when the code is processed by a supporting build tool capable of interpreting Bundle Annotations defined in OSGi Core Release 8.

Specifying CDI bean descriptors - As specified in Bean Descriptors a CDI bundle must declare all CDI bean descriptors CCR is expected to operate on. This is done by adding the attribute descriptor, of type List<String>, to the requirement.

Specifying the list of bean classes - As specified in Bean Discovery a CDI bundle must declare all bean classes CCR is expected to operate on. This is done by adding the attribute beans, of type List<String>, to the requirement.

A capability in the osgi.implementation namespace declaring an implementation with the name osgi.cdi. In addition to the specification packages, this capability must also declare a uses constraint for the javax.enterprise.* packages. For example:

Provide-Capability:
	osgi.implementation;
		osgi.implementation="osgi.cdi";
		version:Version="1.0";
		uses:="javax.enterprise.context, javax.enterprise.context.control,
			javax.enterprise.context.spi, javax.enterprise.event,
			javax.enterprise.inject, javax.enterprise.inject.literal,
			javax.enterprise.inject.spi, javax.enterprise.inject.spi.configurator,
			javax.enterprise.util, org.osgi.service.cdi,
			org.osgi.service.cdi.annotations,
			org.osgi.service.cdi.reference, org.osgi.service.cdi.runtime,
			org.osgi.service.cdi.runtime.dto,
			org.osgi.service.cdi.runtime.dto.template"

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

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

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

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

A capability in the osgi.service namespace for every service declared by the metadata in the CDI bundle.

152.16 Relationship to CDI features

CDI has many features which may occasionally interact with the OSGi CDI integrations defined by this specification.

152.16.1 Bean Descriptors

The [6] Packaging and deployment chapter of the CDI specification defines XML descriptors which are used to control the CDI container. This specification expects that these descriptors be declared using the osgi.cdi extender requirement attribute descriptor of type List<String>. For example:

Require-Capability:
	osgi.extender;
		filter:=”(&(osgi.extender=osgi.cdi)(version>=1.0)(!(version>=2.0.0)))”;
		descriptor:List<String>="META-INF/beans.xml"

If the attribute is not specified the default value of META-INF/beans.xml is used.

CCR must find descriptors by calling Bundle.getResources(String) for each specified value. Note that the accepted syntax for the values is the same as for java.lang.ClassLoader.getResources. See osgi.cdi extender capability.

152.16.2 Bean Discovery

The CDI specification defines 3 bean discover modes which perform runtime class discovery:

  • all - All classes in the jar are passed to the CDI container and processed.

  • none - No classes in the jar are passed to the CDI container. It is assumed however that portable extensions may yet provide beans.

  • annotated (default) - Only classes matching the definition of annotated beans as defined by the [4] Default bean discovery mode are passed to the CDI container and processed.

This specification avoids runtime class analysis concern by ignoring the bean discovery mode specified or implied by the descriptors, requiring bean classes to be pre-calculated at build time such that the CDI container receives a concrete list of classes to process.

It is expected that the aforementioned bean discover modes be implemented in build tooling and be performed at build time.

A CDI bundle must specify the list of classes to process using the osgi.cdi extender requirement attribute beans of type List<String>. For example:

Require-Capability:
	osgi.extender;
		filter:=”(&(osgi.extender=osgi.cdi)(version>=1.0)(!(version>=2.0.0)))”;
		beans:List<String>="org.foo.Bar, org.foo.baz.Fum"

See osgi.cdi extender capability.

152.16.2.1 Build tool support

The bean descriptors specified by the CDI specification allow for narrowing the range of processed classes by defining [5] Exclude filters. While these filters are still considered, they are only applied over the concrete list of classes passed from the beans attribute.

Build tools may opt to implement bean discover modes. Implementing the discovery mode all simply requires placing the names of all classes found in the bundle in the beans attribute. Implementing the discovery mode annotated involves collecting the names of all classes matching the definition of annotated beans as defined by the [4] Default bean discovery mode and placing those in the beans attribute.

Another option is to use the CLASS retention annotation defined by this specification.

The CLASS retention annotation Bean may be applied to a class to indicate to supporting build tools it must be included in the beans list.

The CLASS retention annotation Beans may be applied to a package to indicate to supporting build tools that all classes in the package must be included in the beans list.

Specifying a value indicates to supporting build tools that the specified classes in the package must be included in the beans list.

152.16.3 Portable Extensions

CDI Portable Extensions use CDI's SPI which provides a powerful mechanism for extending the base functionality of CDI. Portable extensions may add, modify or read bean and bean class metadata, define custom contexts, and much more. Through the SPI a portable extension can participate in all aspects of the CDI Container's life cycle.

Portable extensions must be provided as OSGi services using the interface javax.enterprise.inject.spi.Extension. Portable extension services must specify the service property osgi.cdi.extension whose value is a name identifying the functionality provided by the portable extension.

Table 152.7 Portable Extension Service Properties

Service Property Type Description
osgi.cdi.extension

String

The name of the Portable Extension


For example, a portable extension service that provides an implementation of the [14] Java Transaction API should specify the value of it's osgi.cdi.extension service property using the [15] Portable Java Contract name specified for it, which is JavaJTA.

Portable Extension bundles must define a capability using the namespace osgi.cdi.extension having an attribute osgi.cdi.extension whose value is the same as the name specified in the osgi.cdi.extension service property of the portable extension service. The capability must also specify a version attribute of type Version. The capability must also specify a uses directive listing all of the Java packages provided as part of the Portable Extension's API. If the portable extension implements an API specified as a Portable Java Contract the uses list should match the Portable Java Contract.

Provide-Capability:
	osgi.cdi.extension;
		osgi.cdi.extension=JavaJTA;
		version:Version="1.2";
		uses:="javax.transaction,javax.transaction.xa"
		

CDI bundles express a dependency on a portable extension by specifying a requirement in the osgi.cdi.extension namespace whose filter matches a portable extension capability. For example:

Require-Capability:
	osgi.cdi.extension;
		filter:=”(&(osgi.cdi.extension=JavaJTA)(version=1.2))”;

See osgi.cdi extender capability.

A Portable extension bundle must require the osgi.implementation capability from CCR. This requirement will wire the extension bundle to the CCR implementation and ensure that CCR is using the same javax.enterprise.* packages as the portable extension bundle.

Require-Capability:
	osgi.implementation;
		filter:="(&(osgi.implementation=osgi.cdi)(version>=1.0)(!(version>=2.0)))"

The requirement may be specified directly on any class in the portable extension bundle by using the RequireCDIImplementation annotation when the code is processed by tooling capable of interpreting Bundle Annotations defined in OSGi Core Release 8.

152.16.3.1 Portable Extension Services and Beans

Portable extension bundles intending to provide additional beans must do so programmatically using the SPI. Bean descriptors in the bundle providing the portable extension service are not visible to the CDI container and therefore play no role in bean discovery.

152.16.3.2 Embedded Portable Extension

Portable extensions which are embedded in the CDI bundle are discoverable through the CDI specified service loader mechanism using the class loader of the CDI bundle.

152.16.4 Bean Manager

When the container component is satisfied CCR must published the CDI container's javax.enterprise.inject.spi.BeanManager to the service registry using the ServiceContext of the CDI bundle accompanied by the following service property:

Table 152.8 Bean Manager Service Properties

Service Property Type Description
osgi.cdi.container.id

String

The container id. The constant CDI_CONTAINER_ID_PROPERTY exists for convenience. See Container Component.


The javax.enterprise.inject.spi.BeanManager must be unregistered when the container component becomes unsatisfied.

152.16.5 Decorators and Interceptors

Decorators and Interceptors are used to wrap contextual instances with proxies to deliver additional, targeted functionality. However, these features do not support [3] unproxyable bean types. Attempting to apply either feature to a bean or producer having an unproxyable bean type will result in a definition error. This limitation extends to CCR where applicable. The @javax.enterprise.inject.Typed annotation is available to explicitly reduce the set of bean types, making it possible to use either feature on beans having unproxyable types. Implementations of this specification must support the use of @javax.enterprise.inject.Typed when publishing services.

Service objects are the product of beans and producers. As such they may be targeted by Decorators and/or Interceptors and wrapped by proxies. Therefore the subset of types under which the service is published must be a subset of the bean types, including further restrictions declared by @javax.enterprise.inject.Typed. Service types not contained in the restricted set of bean types will result in a definition error. See @Service Type Restrictions.

152.17 Security

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

152.17.1 Service Permissions

CCR dependencies 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, that component cannot be satisfied unless the CDI 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 CDI 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.

CCR must have ServicePermission[CDIComponentRuntime, REGISTER] permission to register the CDIComponentRuntime service. Administrative bundles wishing to use the CDIComponentRuntime service must have ServicePermission[CDIComponentRuntime, 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.

152.17.2 Required Admin Permission

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

152.17.3 Using hasPermission

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

152.17.4 Configuration Multi-Locations and Regions

CCR 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 CCR must act as if the Configuration does not exist for the bundle.

152.18 org.osgi.service.cdi

Version 1.0

CDI Integration Package Version 1.0.

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.cdi; version="[1.0,2.0)"

Example import for providers implementing the API in this package:

Import-Package: org.osgi.service.cdi; version="[1.0,1.1)"

152.18.1 Summary

152.18.2 public class CDIConstants

Defines CDI constants.

Consumers of this API must not implement this type

152.18.2.1 public static final String CDI_CAPABILITY_NAME = "osgi.cdi"

Capability name for CDI Integration.

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

 Require-Capability: osgi.extender; «
  filter:="(&(osgi.extender=osgi.cdi)(version>=1.0)(!(version>=2.0)))"

152.18.2.2 public static final String CDI_COMPONENT_NAME = "$"

Special string representing the name of a Component.

This string can be used with PID OR factory PID to specify the name of the component.

For example:

 @PID(CDI_COMPONENT_NAME)

152.18.2.3 public static final String CDI_CONTAINER_ID = "container.id"

The attribute of the CDI extender requirement declaring the container's id.

 Require-Capability: osgi.extender; «
  filter:="(&(osgi.extender=osgi.cdi)(version>=1.0)(!(version>=2.0)))"; «
  container.id="my.container"

152.18.2.4 public static final String CDI_CONTAINER_ID_PROPERTY = "osgi.cdi.container.id"

The key used for the container id service property in services provided by CCR.

152.18.2.5 public static final String CDI_EXTENSION_PROPERTY = "osgi.cdi.extension"

A service property applied to javax.enterprise.inject.spi.Extension services, whose value is the name of the extension.

152.18.2.6 public static final String CDI_SPECIFICATION_VERSION = "1.0.0"

Compile time constant for the Specification Version of CDI Integration.

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

152.18.2.7 public static final String REQUIREMENT_BEANS_ATTRIBUTE = "beans"

The 'beans' attribute on the CDI extender requirement.

The value of this attribute is a list of bean class names that will be processed by CCR. The default value is an empty list. For example:

 Require-Capability: osgi.extender; «
  filter:="(&(osgi.extender=osgi.cdi)(version>=1.0)(!(version>=2.0)))"; «
  beans:List<String>="com.acme.Foo,com.acme.bar.Baz"

152.18.2.8 public static final String REQUIREMENT_DESCRIPTOR_ATTRIBUTE = "descriptor"

The 'descriptor' attribute on the CDI extender requirement.

The value of this attribute is a list of bean CDI bean descriptor file paths to be searched on the Bundle-ClassPath. For example:

 Require-Capability: osgi.extender; «
  filter:="(&(osgi.extender=osgi.cdi)(version>=1.0)(!(version>=2.0)))"; «
  descriptor:List<String>="META-INF/beans.xml"

152.18.3 enum ComponentType

Define the possible values for ComponentTemplateDTO.type.

152.18.3.1 CONTAINER

The component is the Container Component.

152.18.3.2 SINGLE

The component is an Single Component.

152.18.3.3 FACTORY

The component is an Factory Component.

152.18.3.4 public static ComponentType valueOf(String name)

152.18.3.5 public static ComponentType[] values()

152.18.4 enum ConfigurationPolicy

Defines the possible values for configuration policy.

152.18.4.1 OPTIONAL

Defines the optional configuration policy.

152.18.4.2 REQUIRED

Defines the required configuration policy.

152.18.4.3 public static ConfigurationPolicy valueOf(String name)

152.18.4.4 public static ConfigurationPolicy[] values()

152.18.5 enum MaximumCardinality

Defines the possible values for maximum cardinality of dependencies.

152.18.5.1 ONE

Defines a unary reference.

152.18.5.2 MANY

Defines a plural reference.

152.18.5.3 public static MaximumCardinality fromInt(int value)

The integer representation of an upper cardinality boundary

Resolve an integer to an upper cardinality boundary.

The enum representation of the upper cardinality boundary described by value

152.18.5.4 public int toInt()

Convert this upper cardinality boundary to an integer

The integer representation of this upper cardinality boundary

152.18.5.5 public static MaximumCardinality valueOf(String name)

152.18.5.6 public static MaximumCardinality[] values()

152.18.6 enum ReferencePolicy

Defines the possible values of the policy of a reference towards propagating service changes to the CDI runtime

152.18.6.1 STATIC

Reboot the CDI component that depends on this reference

152.18.6.2 DYNAMIC

Update the CDI reference

152.18.6.3 public static ReferencePolicy valueOf(String name)

152.18.6.4 public static ReferencePolicy[] values()

152.18.7 enum ReferencePolicyOption

Defines the possible values of the policy of a satisfied reference towards new matching services appearing.

152.18.7.1 GREEDY

Consume the matching service applying it's ReferencePolicy

152.18.7.2 RELUCTANT

Do not consume the matching service

152.18.7.3 public static ReferencePolicyOption valueOf(String name)

152.18.7.4 public static ReferencePolicyOption[] values()

152.18.8 enum ServiceScope

Possible values for ActivationTemplateDTO.scope.

152.18.8.1 SINGLETON

This activation will only ever create one instance

The instance is created after the parent component becomes satisfied and is destroyed before the parent component becomes unsatisfied.

If ActivationTemplateDTO.serviceClasses is not empty the instance will be registered as an OSGi service with service.scope=singleton.

152.18.8.2 BUNDLE

This activation will register an OSGi service with service.scope=bundle.

The service is registered just after all SINGLETON activations are set up and just before all SINGLETON activations are torn down.

The ActivationTemplateDTO.serviceClasses is not empty when this scope is used.

152.18.8.3 PROTOTYPE

This activation will register an OSGi service with service.scope=prototype.

The service is registered just after all SINGLETON activations are set up and just before all SINGLETON activations are torn down.

The ActivationTemplateDTO.serviceClasses is not empty when this scope is used.

152.18.8.4 public static ServiceScope valueOf(String name)

152.18.8.5 public static ServiceScope[] values()

152.19 org.osgi.service.cdi.annotations

Version 1.0

CDI Integration Package Version 1.0.

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.cdi.annotations; version="[1.0,2.0)"

Example import for providers implementing the API in this package:

Import-Package: org.osgi.service.cdi.annotations; version="[1.0,1.1)"

152.19.1 Summary

152.19.2 @Bean

Annotation used to indicate that build tooling must be included the class in the osgi.cdi beans list.

CLASS

TYPE

152.19.3 @BeanPropertyType

Identify the annotated annotation as a Bean Property Type.

Bean Property Type can be applied to beans annotated with SingleComponent, FactoryComponent, to beans annotated with ApplicationScoped or Dependent where the Service annotation is applied, to methods and fields marked as Produces where the Service annotation is applied, or to injection points where the Reference annotation is applied.

Bean Property Types.

RUNTIME

ANNOTATION_TYPE

152.19.4 public static final class BeanPropertyType.Literal
extends AnnotationLiteral<BeanPropertyType>
implements BeanPropertyType

Support inline instantiation of the BeanPropertyType annotation.

152.19.4.1 public static final BeanPropertyType INSTANCE

Default instance.

152.19.4.2 public Literal()

152.19.5 @Beans

Annotation used to indicate that build tooling must be included the specified classes in the osgi.cdi beans list.

CLASS

PACKAGE

152.19.5.1 Class<?>[] value default {}

Specify the list of classes from the current package. Specifying no value (or an empty array) indicates to include all classes in the package.

152.19.6 @ComponentProperties

Annotation used with Inject in order to have component properties injected.

See "Component Properties".

RUNTIME

FIELD, PARAMETER

152.19.7 public static final class ComponentProperties.Literal
extends AnnotationLiteral<ComponentProperties>
implements ComponentProperties

Support inline instantiation of the ComponentProperties annotation.

152.19.7.1 public static final ComponentProperties INSTANCE

Default instance.

152.19.7.2 public Literal()

152.19.8 @ComponentScoped

This scope is used to declare a bean who's lifecycle is determined by the state of it's OSGi dependencies and the SingleComponent(s) and FactoryComponent(s) that may reference it through injection.

RUNTIME

FIELD, METHOD, PARAMETER, TYPE

152.19.9 public static final class ComponentScoped.Literal
extends AnnotationLiteral<ComponentScoped>
implements ComponentScoped

Support inline instantiation of the ComponentScoped annotation.

152.19.9.1 public static final ComponentScoped INSTANCE

Default instance.

152.19.9.2 public Literal()

152.19.10 @FactoryComponent

Identifies a factory component.

Factory components MUST always be ComponentScoped. Applying any other scope will result in a definition error.

Factory Component

RUNTIME

TYPE

152.19.10.1 String value default "$"

The configuration PID for the configuration of this Component.

The value specifies a configuration PID who's configuration properties are available at injection points in the component.

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

For example:

 
            @FactoryPID(CDI_COMPONENT_NAME)
         

152.19.11 public static final class FactoryComponent.Literal
extends AnnotationLiteral<FactoryComponent>
implements FactoryComponent

Support inline instantiation of the FactoryComponent annotation.

152.19.11.1 public static final FactoryComponent.Literal of(String pid)

the factory configuration pid

an instance of FactoryComponent

152.19.11.2 public String value()

152.19.12 @MinimumCardinality

Annotation used in conjunction with Reference to specify the minimum cardinality reference property.

Specifying the MinimumCardinality annotation with the value of 0 on a unary reference is a definition error.

RUNTIME

FIELD, PARAMETER

152.19.12.1 int value default 1

The minimum cardinality of the reference.

The value must be a positive integer.

For example:

 
            @MinimumCardinality(3)
         

152.19.13 public static final class MinimumCardinality.Literal
extends AnnotationLiteral<MinimumCardinality>
implements MinimumCardinality

Support inline instantiation of the MinimumCardinality annotation.

152.19.13.1 public static final MinimumCardinality.Literal of(int value)

the minimum cardinality

an instance of MinimumCardinality

152.19.13.2 public int value()

152.19.14 @PID

Annotation used in collaboration with ComponentScoped to specify singleton configurations and their policy.

RUNTIME

FIELD, METHOD, PARAMETER, TYPE

152.19.14.1 String value default "$"

The configuration PID for the configuration of this Component.

The value specifies a configuration PID who's configuration properties are available at injection points in the component.

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

For example:

 
            @PID(CDI_COMPONENT_NAME)
         

152.19.14.2 ConfigurationPolicy policy default OPTIONAL

The configuration policy associated with this PID.

Controls how the configuration must be satisfied depending on the presence and type of a corresponding Configuration object in the OSGi Configuration Admin service. Corresponding configuration is a Configuration object where the PID is equal to value.

If not specified, the configuration is not required.

152.19.15 public static final class PID.Literal
extends AnnotationLiteral<PID>
implements PID

Support inline instantiation of the PID annotation.

152.19.15.1 public static final PID.Literal of(String pid, ConfigurationPolicy policy)

the configuration pid

the policy of the configuration

an instance of PID

152.19.15.2 public ConfigurationPolicy policy()

152.19.15.3 public String value()

152.19.16 @PIDs

Annotation used in conjunction with ComponentScoped in order to associate configurations with the component bean.

RUNTIME

FIELD, METHOD, PARAMETER, TYPE

152.19.16.1 PID[] value

The set of ordered configurations available to the component.

152.19.17 public static final class PIDs.Literal
extends AnnotationLiteral<PIDs>
implements PIDs

Support inline instantiation of the PIDs annotation.

152.19.17.1 public static PIDs of(PID[] pids)

array of PID

an instance of PIDs

152.19.17.2 public PID[] value()

152.19.18 @PrototypeRequired

Used with @Reference, BindService, BindBeanServiceObjects and BindServiceReference to indicate that the service must be service.scope=prototype.

RUNTIME

FIELD, METHOD, PARAMETER, TYPE

152.19.19 public static final class PrototypeRequired.Literal
extends AnnotationLiteral<PrototypeRequired>
implements PrototypeRequired

Support inline instantiation of the PrototypeRequired annotation.

152.19.19.1 public static final PrototypeRequired INSTANCE

Default instance

152.19.19.2 public Literal()

152.19.20 @Reference

Annotation used on injection points informing the CDI container that the injection should apply a service obtained from the OSGi registry.

*

Reference Annotation

RUNTIME

FIELD, PARAMETER

152.19.20.1 Class<?> value default Object.class

Specify the type of the service for this reference.

If not specified, the type of the service for this reference is derived from the injection point type.

If a value is specified it must be type compatible with (assignable to) the service type derived from the injection point type, otherwise a definition error will result.

152.19.20.2 String target default ""

The target property for this reference.

If not specified, no target property is set.

152.19.21 public static final class Reference.Any

A marker type used in Reference.value to indicate that a reference injection point may accept any service type(s).

The injection point service type must be specified as Object.

The value must be specified by itself.

For example:

 @Inject
 @Reference(value = Any.class, target = "(bar=baz)")
 List<Object> services;

152.19.21.1 public Any()

152.19.22 public static final class Reference.Literal
extends AnnotationLiteral<Reference>
implements Reference

Support inline instantiation of the Reference annotation.

152.19.22.1 public static final Reference.Literal of(Class<?> service, String target)

instance of Reference

152.19.22.2 public String target()

152.19.22.3 public Class<?> value()

152.19.23 @Reluctant

Annotation used to indicate that the behavior of the reference should be reluctant. Used in conjunction with @Reference, BindService, BindServiceReference or BindBeanServiceObjects.

RUNTIME

FIELD, METHOD, PARAMETER, TYPE

152.19.24 public static final class Reluctant.Literal
extends AnnotationLiteral<Reluctant>
implements Reluctant

Support inline instantiation of the Reluctant annotation.

152.19.24.1 public static final Reluctant INSTANCE

Default instance

152.19.24.2 public Literal()

152.19.25 @RequireCDIExtender

This annotation can be used to require the CDI Component Runtime extender. It can be used directly, or as a meta-annotation.

CLASS

TYPE, PACKAGE

152.19.25.1 String[] descriptor default "META-INF/beans.xml"

Specify CDI bean descriptor file paths to be searched on the Bundle-ClassPath. For example:

 @RequireCDIExtender(descriptor = "META-INF/beans.xml")

CDI bean descriptor file paths.

152.19.25.2 Class<?>[] beans default {}

Specify OSGi Beans classes to be used by the CDI container. For example:

 @RequireCDIExtender(beans = {com.foo.BarImpl.class, com.foo.impl.BazImpl.class})

OSGi Beans classes to be used by the CDI container.

152.19.26 @RequireCDIImplementation

This annotation can be used to require the CDI Component Runtime implementation. It can be used directly, or as a meta-annotation.

CLASS

TYPE, PACKAGE

152.19.27 @Service

Annotation used to specify that a bean should be published as a service.

The behavior of this annotation depends on it's usage:

  • on the bean type - publish the service using all implemented interfaces. If there are no implemented interfaces use the bean class.

  • on the bean's type_use(s) - publish the service using the collected interface(s).

Use of @Service on both type and type_use will result in a definition error.

Where this annotation is used affects how service scopes are supported:

  • @SingleComponent, @FactoryComponent or @Dependent bean - The provided service can be of any scope. The bean can either implement ServiceFactory or PrototypeServiceFactory or use @Bundle or @Prototype to set it's service scope. If none of those options are used the service is a singleton scope service.

  • @ApplicationScoped bean - The provided service is a singleton scope service unless the bean implements ServiceFactory or PrototypeServiceFactory. It cannot use @Bundle or @Prototype to set it's service scope. Use of those annotations in this case will result in a definition error.

RUNTIME

FIELD, METHOD, TYPE, TYPE_USE

152.19.27.1 Class<?>[] value default {}

Override the interfaces under which this service is published.

the service types

152.19.28 public static final class Service.Literal
extends AnnotationLiteral<Service>
implements Service

Support inline instantiation of the Service annotation.

152.19.28.1 public static final Service.Literal of(Class<?>[] interfaces)

instance of Service

152.19.28.2 public Class<?>[] value()

152.19.29 @ServiceInstance

Annotation used on beans, observer methods and observer fields to specify the service scope for the service. Used in conjunction with Service.

RUNTIME

TYPE, FIELD, METHOD

152.19.29.1 ServiceScope value default SINGLETON

The scope of the service.

152.19.30 public static final class ServiceInstance.Literal
extends AnnotationLiteral<ServiceInstance>
implements ServiceInstance

Support inline instantiation of the ServiceInstance annotation.

152.19.30.1 public static ServiceInstance.Literal of(ServiceScope type)

the type of the ServiceInstance

an instance of ServiceInstance

152.19.30.2 public ServiceScope value()

152.19.31 @SingleComponent

Identifies a single component.

Single components MUST always be ComponentScoped. Applying any other scope will result in a definition error.

Single Component

RUNTIME

TYPE

152.19.32 public static final class SingleComponent.Literal
extends AnnotationLiteral<SingleComponent>
implements SingleComponent

Support inline instantiation of the SingleComponent annotation.

152.19.32.1 public static final SingleComponent INSTANCE

Default instance.

152.19.32.2 public Literal()

152.20 org.osgi.service.cdi.propertytypes

Version 1.0

Bean Property Types Package Version 1.0.

When used as annotations, bean property types are processed by CCR to generate default component properties, service properties and target filters.

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.cdi.propertytypes; version="[1.0,2.0)"

152.20.1 Summary

  • BeanPropertyException - This Runtime Exception is thrown when a Bean Property Type method attempts an invalid component property coercion.

  • ExportedService - Bean Property Type for the remote service properties for an exported service.

  • ServiceDescription - Bean Property Type for the service.description service property.

  • ServiceRanking - Bean Property Type for the service.ranking service property.

  • ServiceVendor - Bean Property Type for the service.vendor service property.

152.20.2 public class BeanPropertyException
extends RuntimeException

This Runtime Exception is thrown when a Bean Property Type method attempts an invalid component property coercion. For example when the bean property type method Long test(); is applied to a component property "test" of type String.

152.20.2.1 public BeanPropertyException(String message)

The message for this exception.

Create a Bean Property Exception with a message.

152.20.2.2 public BeanPropertyException(String message, Throwable cause)

The message for this exception.

The causing exception.

Create a Bean Property Exception with a message and a nested cause.

152.20.3 @ExportedService

Bean Property Type for the remote service properties for an exported service.

This annotation can be used as defined by BeanPropertyType to declare the values of the remote service properties for an exported service.

Bean Property Types, Remote Services Specification

RUNTIME

FIELD, METHOD, PARAMETER, TYPE

152.20.3.1 Class<?>[] service_exported_interfaces

Service property marking the service for export. It defines the interfaces under which the service can be exported.

If an empty array is specified, the property is not added to the component description.

The exported service interfaces.

Constants.SERVICE_EXPORTED_INTERFACES

152.20.3.2 String[] service_exported_configs default {}

Service property identifying the configuration types that should be used to export the service.

If an empty array is specified, the default value, the property is not added to the component description.

The configuration types.

Constants.SERVICE_EXPORTED_CONFIGS

152.20.3.3 String[] service_exported_intents default {}

Service property identifying the intents that the distribution provider must implement to distribute the service.

If an empty array is specified, the default value, the property is not added to the component description.

The intents that the distribution provider must implement to distribute the service.

Constants.SERVICE_EXPORTED_INTENTS

152.20.3.4 String[] service_exported_intents_extra default {}

Service property identifying the extra intents that the distribution provider must implement to distribute the service.

If an empty array is specified, the default value, the property is not added to the component description.

The extra intents that the distribution provider must implement to distribute the service.

Constants.SERVICE_EXPORTED_INTENTS_EXTRA

152.20.3.5 String[] service_intents default {}

Service property identifying the intents that this service implements.

If an empty array is specified, the default value, the property is not added to the component description.

The intents that the service implements.

Constants.SERVICE_INTENTS

152.20.4 @ServiceDescription

Bean Property Type for the service.description service property.

This annotation can be used as defined by BeanPropertyType to declare the value the Constants.SERVICE_DESCRIPTION service property.

Bean Property Types

RUNTIME

FIELD, METHOD, PARAMETER, TYPE

152.20.4.1 String value

Service property identifying a service's description.

The service description.

Constants.SERVICE_DESCRIPTION

152.20.5 @ServiceRanking

Bean Property Type for the service.ranking service property.

This annotation can be used as defined by BeanPropertyType to declare the value of the Constants.SERVICE_RANKING service property.

Bean Property Types

RUNTIME

FIELD, METHOD, PARAMETER, TYPE

152.20.5.1 int value

Service property identifying a service's ranking.

The service ranking.

Constants.SERVICE_RANKING

152.20.6 @ServiceVendor

Bean Property Type for the service.vendor service property.

This annotation can be used as defined by BeanPropertyType to declare the value of the Constants.SERVICE_VENDOR service property.

Bean Property Types

RUNTIME

FIELD, METHOD, PARAMETER, TYPE

152.20.6.1 String value

Service property identifying a service's vendor.

The service vendor.

Constants.SERVICE_VENDOR

152.21 org.osgi.service.cdi.reference

Version 1.0

CDI Integration Package Version 1.0.

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.cdi.annotations; version="[1.0,2.0)"

Example import for providers implementing the API in this package:

Import-Package: org.osgi.service.cdi.annotations; version="[1.0,1.1)"

152.21.1 Summary

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

  • BindBeanServiceObjects - A bean provided by CCR for binding actions to life cycle events of matching services.

  • BindService - A bean provided by CCR for binding actions to life cycle events of matching services.

  • BindServiceReference - A bean provided by CCR for binding actions to life cycle events of matching services.

152.21.2 public interface BeanServiceObjects<S>

Type of Service

Allows multiple service objects for a service to be obtained.

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

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 BeanServiceObjects object are automatically released by Service Component Runtime when the service becomes unbound.

ServiceObjects

Thread-safe

Consumers of this API must not implement this type

152.21.2.1 public S getService()

Returns a service object for the associated service.

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

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

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

ungetService(Object)

152.21.2.2 public ServiceReference<S> getServiceReference()

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

The ServiceReference for the service associated with this BeanServiceObjects object.

152.21.2.3 public void ungetService(S service)

A service object previously provided by this ReferenceServiceObjects 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 ReferenceServiceObjects object has been deactivated.

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

getService()

152.21.3 public interface BindBeanServiceObjects<S>

the service argument type.

A bean provided by CCR for binding actions to life cycle events of matching services.

Reference

Consumers of this API must not implement this type

152.21.3.1 public BindBeanServiceObjects<S> adding(Consumer<BeanServiceObjects<S>> action)

the action, whose argument is the Bean Service Objects, to subscribe to the adding service event

Subscribe an action to the adding service event.

Only the last adding action is used.

self

IllegalStateException– when called after bind

152.21.3.2 public void bind()

The bind terminal operation is required to instruct CCR that all the bind actions have been specified, otherwise bind actions will never be called by CCR.

Calling bind again has no effect.

152.21.3.3 public BindBeanServiceObjects<S> modified(Consumer<BeanServiceObjects<S>> action)

the action, whose argument is the Bean Service Objects, to subscribe to the modified service event

Subscribe an action to the modified service event.

Only the last modified action is used.

self

IllegalStateException– when called after bind

152.21.3.4 public BindBeanServiceObjects<S> removed(Consumer<BeanServiceObjects<S>> action)

the action, whose argument is the Bean Service Objects, to subscribe to the removed service event

Subscribe an action to the removed service event.

Only the last removed action is used.

self

IllegalStateException– when called after bind

152.21.4 public interface BindService<S>

the service argument type.

A bean provided by CCR for binding actions to life cycle events of matching services.

Reference

Consumers of this API must not implement this type

152.21.4.1 public BindService<S> adding(Consumer<S> action)

the action, whose argument is the service instance, to subscribe to the adding service event

Subscribe an action to the adding service event.

Only the last adding action is used.

self

IllegalStateException– when called after bind

152.21.4.2 public BindService<S> adding(BiConsumer<S, Map<String, Object>> action)

the action, whose arguments are the service instance and the Map<String, Object> of service properties, to subscribe to the adding service event

Subscribe an action to the adding service event.

Only the last adding action is used.

self

IllegalStateException– when called after bind

152.21.4.3 public void bind()

The bind terminal operation is required to instruct CCR that all the bind actions have been specified, otherwise bind actions will never be called by CCR.

Calling bind again has no effect.

152.21.4.4 public BindService<S> modified(Consumer<S> action)

the action, whose argument is the service instance, to subscribe to the modified service event

Subscribe an action to the modified service event.

Only the last modified action is used.

self

IllegalStateException– when called after bind

152.21.4.5 public BindService<S> modified(BiConsumer<S, Map<String, Object>> action)

the action, whose arguments are the service instance and the Map<String, Object> of service properties, to subscribe to the modified service event

Subscribe an action to the modified service event.

Only the last modified action is used.

self

IllegalStateException– when called after bind

152.21.4.6 public BindService<S> removed(Consumer<S> action)

the action, whose argument is the service instance, to subscribe to the removed service event

Subscribe an action to the removed service event.

Only the last removed action is used.

self

IllegalStateException– when called after bind

152.21.4.7 public BindService<S> removed(BiConsumer<S, Map<String, Object>> action)

the action, whose arguments are the service instance and the Map<String, Object> of service properties, to subscribe to the removed service event

Subscribe an action to the removed service event.

Only the last removed action is used.

self

IllegalStateException– when called after bind

152.21.5 public interface BindServiceReference<S>

the service argument type.

A bean provided by CCR for binding actions to life cycle events of matching services.

Reference

Consumers of this API must not implement this type

152.21.5.1 public BindServiceReference<S> adding(Consumer<ServiceReference<S>> action)

the action, whose argument is the service reference, to subscribe to the adding service event

Subscribe an action to the adding service event.

Only the last adding action is used.

self

IllegalStateException– when called after bind

152.21.5.2 public BindServiceReference<S> adding(BiConsumer<ServiceReference<S>, S> action)

the action, whose arguments are the service reference and the service object, to subscribe to the adding service event

Subscribe an action to the adding service event.

Only the last adding action is used.

self

IllegalStateException– when called after bind

152.21.5.3 public void bind()

The bind terminal operation is required to instruct CCR that all the bind actions have been specified, otherwise bind actions will never be called by CCR.

Calling bind again has no effect.

152.21.5.4 public BindServiceReference<S> modified(Consumer<ServiceReference<S>> action)

the action, whose argument is the service reference, to subscribe to the modified service event

Subscribe an action to the modified service event.

Only the last modified action is used.

self

IllegalStateException– when called after bind

152.21.5.5 public BindServiceReference<S> modified(BiConsumer<ServiceReference<S>, S> action)

the action, whose arguments are the service reference and the service object, to subscribe to the modified service event

Subscribe an action to the modified service event.

Only the last modified action is used.

self

IllegalStateException– when called after bind

152.21.5.6 public BindServiceReference<S> removed(Consumer<ServiceReference<S>> action)

the action, whose argument is the service reference, to subscribe to the removed service event

Subscribe an action to the removed service event.

Only the last removed action is used.

self

IllegalStateException– when called after bind

152.21.5.7 public BindServiceReference<S> removed(BiConsumer<ServiceReference<S>, S> action)

the action, whose arguments are the service reference and the service object, to subscribe to the removed service event

Subscribe an action to the removed service event.

Only the last removed action is used.

self

IllegalStateException– when called after bind

152.22 org.osgi.service.cdi.runtime

Version 1.0

CDI Integration Package Version 1.0.

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.cdi; version="[1.0,2.0)"

Example import for providers implementing the API in this package:

Import-Package: org.osgi.service.cdi; version="[1.0,1.1)"

152.22.1 Summary

152.22.2 public interface CDIComponentRuntime

The CDIComponentRuntime service represents the actor that manages the CDI containers and their life cycle. The CDIComponentRuntime service allows introspection of the managed CDI containers.

This service must be registered with a Constants.SERVICE_CHANGECOUNT service property that must be updated each time any of the DTOs available from this service change.

Access to this service requires the ServicePermission[CDIComponentRuntime, 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.

Thread-safe

Consumers of this API must not implement this type

152.22.2.1 public Collection<ContainerDTO> getContainerDTOs(Bundle... bundles)

The bundles who's container description snapshots are to be returned. Specifying no bundles, or the equivalent of an empty Bundle array, will return the container descriptions of all active bundles that define a container.

Returns a collection of container description snapshots for a set of bundles.

A set of descriptions of the container of the specified bundles. Only bundles that have an associated container are included. If a bundle is listed multiple times in bundles only one ContainerDTO is returned. Returns an empty collection if no CDI containers are found.

152.22.2.2 public ContainerTemplateDTO getContainerTemplateDTO(Bundle bundle)

The bundle defining a container. Must not be null and must be active.

Returns the ContainerTemplateDTO for the specified bundle

The container template for of the specified bundle or null if it does not have an associated container.

152.23 org.osgi.service.cdi.runtime.dto

Version 1.0

CDI Integration Package Version 1.0.

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.cdi.dto; version="[1.0,2.0)"

Example import for providers implementing the API in this package:

Import-Package: org.osgi.service.cdi.dto; version="[1.0,1.1)"

152.23.1 Summary

152.23.2 public class ActivationDTO
extends DTO

A snapshot of the runtime state of a component activation.

Not Thread-safe

152.23.2.1 public List<String> errors

The list of errors which occurred during initialization. An empty list means there were no errors.

Must not be null.

152.23.2.2 public ServiceReferenceDTO service

The service this activation may have registered.

Must not be null if template.serviceClasses is not empty.

152.23.2.3 public ActivationTemplateDTO template

The template describing this activation.

Must not be null

152.23.2.4 public ActivationDTO()

152.23.3 public class ComponentDTO
extends DTO

A snapshot of the runtime state of a component.

Not Thread-safe

152.23.3.1 public boolean enabled

Indicates if the component is enabled. The default is true.

A setting of false on the container component results in all components in the bundle being disabled.

152.23.3.2 public List<ComponentInstanceDTO> instances

The component instances created by this component.

Must not be null

152.23.3.3 public ComponentTemplateDTO template

The template of this component.

Must not be null

152.23.3.4 public ComponentDTO()

152.23.4 public class ComponentInstanceDTO
extends DTO

A snapshot of the runtime state of a component.

Not Thread-safe

152.23.4.1 public List<ActivationDTO> activations

The activations of the component.

Must not be null.

152.23.4.2 public List<ConfigurationDTO> configurations

The configuration dependencies of this component.

Must not be null.

152.23.4.3 public Map<String, Object> properties

The resolved configuration properties for the component.

Contains the merger of all consumed configurations merged in the order of configurations.

All configuration dependencies are satisfied when not null.

152.23.4.4 public List<ReferenceDTO> references

The service dependencies of the component.

Can be empty when the component has no reference dependencies.

The component instance is satisfied when the sum of ReferenceDTO.minimumCardinality equals the size of ReferenceDTO.matches for each value.

Must not be null.

152.23.4.5 public ComponentInstanceDTO()

152.23.5 public class ConfigurationDTO
extends DTO

A snapshot of the runtime state of a component factory configuration dependency

Not Thread-safe

152.23.5.1 public Map<String, Object> properties

The properties of this configuration.

The configuration dependency is satisfied when not null.

152.23.5.2 public ConfigurationTemplateDTO template

The template of this configuration dependency

Must never be null

152.23.5.3 public ConfigurationDTO()

152.23.6 public class ContainerDTO
extends DTO

A snapshot of the runtime state of a CDI container

Not Thread-safe

152.23.6.1 public BundleDTO bundle

The bundle declaring the CDI container.

Must not be 0.

152.23.6.2 public long changeCount

The change count of the container at the time this DTO was created

Must not be 0.

152.23.6.3 public List<ComponentDTO> components

The components defined by this CDI container.

Must not be null. The list always contains at least one element representing the container component. See Container Component.

152.23.6.4 public List<String> errors

The list of errors reported during attempted initialization of the container instance.

152.23.6.5 public List<ExtensionDTO> extensions

The extension dependencies of this CDI container.

Must not be null.

152.23.6.6 public ContainerTemplateDTO template

The template of this Container DTO.

Must not be null.

152.23.6.7 public ContainerDTO()

152.23.7 public class ExtensionDTO
extends DTO

A snapshot of the runtime state of an javax.enterprise.inject.spi.Extension dependency required by this CDI container.

Not Thread-safe

152.23.7.1 public ServiceReferenceDTO service

The service reference of the extension.

The extension dependency is satisfied when not null.

152.23.7.2 public ExtensionTemplateDTO template

The template of this extension dependency.

Must not be null

152.23.7.3 public ExtensionDTO()

152.23.8 public class ReferenceDTO
extends DTO

A snapshot of the runtime state of a component reference dependency

Not Thread-safe

152.23.8.1 public List<ServiceReferenceDTO> matches

The list of service references that match this reference.

Must not be null

Can be empty when there are no matching services.

This dependency is satisfied when minimumCardinality <= matches.size() <= MaximumCardinality.toInt() where the maximum cardinality can be obtained from the associated ReferenceTemplateDTO.

152.23.8.2 public int minimumCardinality

The runtime minimum cardinality of the dependency.

152.23.8.3 public String targetFilter

Indicates the runtime target filter used in addition to the template.serviceType to match services.

152.23.8.4 public ReferenceTemplateDTO template

The template of this reference.

Must not be null

152.23.8.5 public ReferenceDTO()

152.24 org.osgi.service.cdi.runtime.dto.template

Version 1.0

CDI Integration Package Version 1.0.

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.cdi.dto.model; version="[1.0,2.0)"

Example import for providers implementing the API in this package:

Import-Package: org.osgi.service.cdi.dto.model; version="[1.0,1.1)"

152.24.1 Summary

152.24.2 public class ActivationTemplateDTO
extends DTO

Activations represent either immediate instances or service objects produced by component instances.

The content of this DTO is resolved form metadata at initialization time and remains the same between the CDI bundle restarts.

Not Thread-safe

152.24.2.1 public Map<String, Object> properties

The default properties for activations which represent container component services. This will never be populated for single or factory components.

These are merged (and possibly replaced) with runtime properties.

Must not be null. May be empty if no default properties are provided.

152.24.2.2 public ServiceScope scope

The ServiceScope of this activation

Must not be null.

152.24.2.3 public List<String> serviceClasses

Describes the set of fully qualified names of the interfaces/classes under which this activation will publish and OSGi service

Must not be null. An empty array indicated this activation will not publish an OSGi service

152.24.2.4 public ActivationTemplateDTO()

152.24.3 public class ComponentTemplateDTO
extends DTO

A static description of a CDI component.

At runtime it is spit between a ComponentInstanceDTO which handles the resolution of the configurations, references and the creation of ComponentInstanceDTO instances and one or more ComponentInstanceDTO instances, which handle the resolution of references and the creation of activations.

Not Thread-safe

152.24.3.1 public List<ActivationTemplateDTO> activations

The activations associated with the component.

Must not be null.

152.24.3.2 public List<String> beans

The set of beans that make up the component.

Must not be null.

152.24.3.3 public List<ConfigurationTemplateDTO> configurations

The configuration dependencies of this component.

There is always at least one default singleton configuration.

May contain at most one factory configuration.

Must not be null.

152.24.3.4 public String name

A name unique within the container.

Must not be null.

152.24.3.5 public Map<String, Object> properties

The default component properties.

These are merged (and possibly replaced) with runtime properties.

Must not be null. May be empty if no default properties are provided.

152.24.3.6 public List<ReferenceTemplateDTO> references

The service dependencies of the component.

The list will be empty if there are no service dependencies.

Must not be null.

152.24.3.7 public ComponentType type

The type of the component.

Must not be null.

152.24.3.8 public ComponentTemplateDTO()

152.24.4 public class ConfigurationTemplateDTO
extends DTO

A description of a configuration dependency of a component The content of this DTO is resolved form metadata at initialization time and remains the same between the CDI bundle restarts.

Not Thread-safe

152.24.4.1 public MaximumCardinality maximumCardinality

The maximum cardinality of the configuration dependency.

Must not be null.

152.24.4.2 public String pid

The PID of the tracked configuration object(s).

Must not be null.

152.24.4.3 public ConfigurationPolicy policy

The policy for the configuration dependency.

Must not be null.

152.24.4.4 public ConfigurationTemplateDTO()

152.24.5 public class ContainerTemplateDTO
extends DTO

Description of a CDI container.

Not Thread-safe

152.24.5.1 public List<ComponentTemplateDTO> components

The components defined in this CDI container.

Must not be null

Has at lest one element for the container component. See Container Component.

152.24.5.2 public List<ExtensionTemplateDTO> extensions

The extension dependencies of this CDI container.

Must not be null

May be empty if the CDI container does not require CDI extensions.

152.24.5.3 public String id

The id of the CDI container.

152.24.5.4 public ContainerTemplateDTO()

152.24.6 public class ExtensionTemplateDTO
extends DTO

Models an extension dependency of the ContainerDTO

Not Thread-safe

152.24.6.1 public String serviceFilter

The service filter used for finding the extension service.

The value must be associated to the osgi.cdi extender requirement whose 'extension' attribute contains a value equal to serviceFilter.

Must not be null.

152.24.6.2 public ExtensionTemplateDTO()

152.24.7 public class ReferenceTemplateDTO
extends DTO

A description of a reference dependency of a component

The content of this DTO is resolved form metadata at initialization time and remains the same between the CDI bundle restarts.

Not Thread-safe

152.24.7.1 public MaximumCardinality maximumCardinality

The maximum cardinality of the reference.

152.24.7.2 public int minimumCardinality

The minimum cardinality of the reference.

Contains the minimum cardinality statically resolved from the CDI bundle metadata. The minimum cardinality can be replaced by configuration at runtime.

152.24.7.3 public String name

A unique within the container and persistent across reboots identified for this activation

The value must not be null. The value must be equal to the reference name.

152.24.7.4 public ReferencePolicy policy

Indicates if the reference is dynamic or static in nature.

152.24.7.5 public ReferencePolicyOption policyOption

Indicates if the reference is greedy or reluctant in nature.

152.24.7.6 public String serviceType

Indicates the type of service matched by the reference.

The value must not be null.

152.24.7.7 public String targetFilter

Indicates a target filter used in addition to the serviceType to match services.

Contains the target filter resolved from the CDI bundle metadata. The filter can be replaced by configuration at runtime.

152.24.7.8 public ReferenceTemplateDTO()