Java Reference
In-Depth Information
£
£
€
LSE
LSE
DAX
d
e
f
$
NYSE
b
OSGi
service
registry
KRX
ServiceReference
c
ctx.getServiceReference ( )
Figure 4.12
Discovering an OSGi service
Here's how you can find all stock listing services using the
GBP
currency:
ServiceReference[] references =
bundleContext.getServiceReferences(StockListing.class.getName(),
"(currency=GBP)");
This returns references to the two
LSE
services (
service.id
s 3 and 4 in figure 4.12).
You can also use the
objectClass
property, mentioned in table 4.2, to query for
services that provide specific additional interfaces. Here, you narrow the search to
those stock listing services that use a currency of
GBP
and also provide a chart service:
ServiceReference[] references =
bundleContext.getServiceReferences(StockListing.class.getName(),
"(&(currency=GBP)(objectClass=org.example.StockChart))");
This returns only one
LSE
service reference (
service.id
4 from figure 4.12) because
the other
LSE
service provides listings, but not charts.
You can look up all sorts of service references based on your needs, but how do you
use them? You need to dereference each service reference to get the actual service
object.
USING A SERVICE
Before you can use a service, you must bind to the actual implementation from the
registry, like this:
StockListing listing =
(StockListing) bundleContext.getService(reference);
The implementation returned is typically exactly the same
POJO
instance previously
registered with the registry, although the
OSG
i specification doesn't prohibit the use
of proxies or wrappers.