Java Reference
In-Depth Information
(continued)
It also risks losing state if unget() is called with a stateful service. Even worse, noth-
ing is done to handle the case when the service is dynamically unregistered. For more
correct behavior, you'd need to introduce service listeners or service trackers. If your
head is spinning at this point with all the APIs and complications, don't worry—treat
listings 6.2 and 6.3 as examples of what you won't be doing, because you'll be using
dependency injection for your services instead!
Even if multiple services which implement the SpecialOffer interface are available, the
code in listing 6.2 will only return the top-ranked service. To get all the available services,
use the getServiceReferences method instead. You'll also need to use getServiceRef-
erences if you want to filter the returned services based on their service properties.
Listing 6.3
Consuming multiple OSGi services using the OSGi API
public void callServices(BundleContext ctx)
throws InvalidSyntaxException {
Filter services
based on
properties.
ServiceReference[] refs = ctx.getServiceReferences(
"fancyfoods.food.SpecialOffer",
"(myStringProperty=foo)");
Check for null ...
if (refs != null) {
for (ServiceReference ref : refs) {
SpecialOffer s = (SpecialOffer) ctx.getService(ref);
if (s != null) {
try {
Food f = s.getOfferFood();
} finally {
ctx.ungetService(ref);
... and check
again.
You must unget every
service found.
}
}
}
}
}
As before, you need to be diligent about checking for null service references and null
service instances, and also in ungetting any services you get.
Type safety and the Service Registry
You may have noticed that listings 6.2 and 6.3 have to cast the service object to its
interface type. Newer versions of the OSGi framework offer methods that take Class
objects rather than String class names. These methods use Java generics to en-
sure type safety and remove the need to cast your service objects.
You could have used these methods to get slightly neater code in your examples, but
existing code you see in the real world will almost certainly have been written using
the older String versions of these methods.
Search WWH ::




Custom Search