Java Reference
In-Depth Information
Registering and looking up services the old-fashioned way
You've already been using OSG i services extensively in chapters 2 and 3. If you don't
recall a discussion of OSG i services, you're probably not alone—you've always used
Blueprint to manage your services. As you'll see, there was a good reason for this!
Let's see what OSG i services look like without a helper framework. Registering OSG i
services is easy; it's a single API call. The following listing shows how to register a ser-
vice of class DesperateCheeseOffer that exposes the interface SpecialOffer .
Listing 6.1
Registering an OSGi service using the OSGi API
public void registerService(BundleContext ctx) {
String iface = SpecialOffer.class.getName();
Dictionary<String, Object> props =
new Hashtable<String, Object>();
props.put("myStringProperty", "foo");
props.put("myBooleanProperty", Boolean.TRUE);
SpecialOffer impl = new DesperateCheeseOffer();
ServiceRegistration reg =
ctx.registerService(iface, impl, props);
the service
The service is registered under a string representing an interface name, and to pre-
vent an error at runtime, the service object has to implement that interface. Optional
properties describing the service can also be added. An object representing the ser-
vice is instantiated, and then the name, properties, and instance are passed to the
bundle context for registration with the OSG i framework. The returned Service-
Registration can be used to unregister or update the service if you need to at some
point in the future.
Consuming OSG i services appears to be equally easy, requiring only two API calls. But
this isn't the whole story. You may have guessed that we're keen to impress upon you
that an OSG i framework is a dynamic place. Services can come and go at any moment,
including the instant that you have looked them up! If you want to use services prop-
erly, it takes more code than the bare minimum two calls. You have to be particularly
careful to always unget a service when you're done with it. Listings 6.2 and 6.3 show
code calling out to services in the Service Registry.
Ungetting services
The get/release pattern can be the source of a lot of problems in computing, and
many people are confused by why it's needed in the OSGi Service Registry. Typically,
in Java the only things that you release after use are I/O streams.
Search WWH ::

Custom Search