Java Reference
In-Depth Information
because you need it to create the window for the paint program. For components that
don't provide a service, it's an error to set immediate to false because they would
never be instantiated; instead, they're implicitly defined as immediate components.
COMPONENT FACTORIES
The final tool in the Declarative Services toolbox is component factories. These pro-
vide a programmatic mechanism to instantiate new instances of components. In many
ways, this is similar to the factory PID mechanism of creating components mentioned
earlier; but instead of going via the ConfigurationAdmin interface, the Declarative
Services specification provides a mechanism to declare a component as explicitly pro-
viding a factory API , which is then manipulated by a secondary service to construct
actual instances of the components.
To see how this works, let's consider a slight variation of the original paint example
where a shape component factory is registered to provide shape components on
demand. You create a component factory by declaring the component using the
factory=<factory.identifier> attribute on the top-level component declaration:
<scr:component xmlns:scr=http://www.osgi.org/xmlns/scr/v1.1.0
factory="shape.factory" name="shape">
This results in the Declarative Services framework publishing a ComponentFactory ser-
vice into the service registry. Component factory services can be used like any normal
services; for example, client code wishing to be injected with this component factory
can do the following:
<reference
name="shape"
interface="org.osgi.service.component.ComponentFactory"
target="(component.factory=shape.factory)"
cardinality="1..1"
policy="static"
bind="addShapeFactory"
unbind="removeShapeFactory"/>
Here the target attribute of the reference element is set to the name of the factory
attribute of the declared component. To create a new shape instance, you use the fol-
lowing code.
Listing 11.7 Using a component factory
import org.osgi.service.component.ComponentFactory;
public class ShapeManager {
private AtomicReference<ComponentFactory> factoryRef =
new AtomicReference<ComponentFactory>();
void addShapeFactory(ComponentFactory factory) {
factoryRef.set(factory);
}
B
Registers
component factory
void removeShapeFactory(ComponentFactory factory) {
factoryRef.set(null);
 
Search WWH ::




Custom Search