Java Reference
In-Depth Information
Lookup strategy
So far in this section, we've shown you how to inject services into components using
binding methods. This pattern is known as the
Hollywood principle
: “Don't call us,
we'll call you.” In some circumstances, it's useful to apply the Reverse Hollywood
principle, “Do call us, we won't call you.”
The Declarative Services specification supports both approaches; it refers to the in-
jection approach as the
event strategy
and the alternative as the
lookup strategy
. The
event strategy provides instant notification about service changes, whereas the look-
up strategy is able to defer service creation until the last minute.
The family of
locateService()
methods on the
ComponentContext
facilitate the
lookup strategy. These methods each take a
String
argument that specifies the name
of the associated service reference in the component description XML file to retrieve.
For example, you could change the paint frame description to be the following:
<scr:reference
interface="org.foo.shape.SimpleShape"
cardinality="0..n"
policy="dynamic"
name="shape"/>
In this case, you don't have bind or unbind methods. To access any bound services,
you need to use the
ComponentContext
, like this:
void findShapes(ComponentContext ctx) {
Object[] services = ctx.locateServices("shape");
for (Object s : services) {
SimpleShape shape = (SimpleShape) s;
}
}
It's possible to mix and match these approaches. You can use the event strategy for
some service references and the lookup strategy for others. You can even use a hy-
brid approach, using the event strategy with a binding method accepting a
Service-
Reference
combined with the
locateService(String,
ServiceReference)
method of the
ComponentContext
. This option provides a highly responsive but light-
weight approach to service binding.
CONFIGURATION POLICY
We've mentioned that it's possible to configure a Declarative Services component by
specifying an entry in the Configuration Admin Service with
PID
corresponding to the
name of the component. These configuration properties override any specified in the
XML
description and provide a way to tweak the behavior of a component at execu-
tion time. It's also possible to define a policy for how dependencies on configuration
properties should be handled.
Declarative Services defines the following configuration policies:
optional
,
require
, and
ignore
. The default configuration policy is
optional
, indicating that
Configuration Admin will be used if available. If
require
is specified, the component