Java Reference
In-Depth Information
A.5.2
Accessing services
In conventional OSG i, services are looked up using the bundle context. As you've
seen, enterprise OSG i allows services to be accessed declaratively instead. This is
almost always a best practice, because it's both easier and more robust. What are you
missing out on by using Blueprint? The following example looks up a service, but
without any error-handling code:
String interfaceName = SpecialOffer.class.getName();
ServiceReference ref = ctx.getServiceReference(interfaceName);
SpecialOffer lister = (SpecialOffer) ctx.getService(ref);
After you've added in code for error-handling, cleanup, and accounted for OSG i's
dynamism, the code to cleanly look up a service is much longer. Almost every line
needs a null check. This is why Blueprint is a best practice!
Cleaning up afterwards
When code is done with a service, it should call ungetService to release the ser-
vice. Forgetting to unget services prevents the framework from being able to free up
the resources associated with a service, and may prevent an application from oper-
ating properly.
When using the standard lookup method, the OSG i framework ensures that you only
ever find services that share your class space for their declared API . This guarantees
that you can always use any service that you find using that method, though it does
sometimes lead to some confusing debugging when a lookup ignores a seemingly
good service!
C ONSUMING MULTIPLE SERVICES
What happens when multiple providers of the service have been registered? The ser-
vice consumer has a choice between getting one, or getting a list containing all of
them (see figure A.8). If the service is something like a credit card processing service,
it's only necessary to take a payment once. In this situation, one service provider is suf-
ficient, and it probably doesn't matter too much which provider is chosen. In the case
of a logging service, on the other hand, logged messages should be sent to all the
available loggers as follows, rather than one of them:
ServiceReference[] refs = ctx.getServiceReferences(Logger.class
.getName());
if (refs != null) {
for (ServiceReference ref : refs) {
Logger logger = (Logger) ctx.getService(ref);
logger.doSomeLogging();
Go through each
service reference
}
}
Search WWH ::




Custom Search