Java Reference
In-Depth Information
All service implementations are ultimately packaged into a bundle, and that bun-
dle must be lifecycle aware in order to register the service. This means you need to
create a bundle activator for the example service, as shown next.
Listing 1.6 OSGi bundle activator with service registration
package org.foo.hello.impl;
import org.foo.hello.Greeting;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
public void start(BundleContext ctx) {
ctx.registerService(Greeting.class.getName(),
new GreetingImpl("service"), null);
}
public void stop(BundleContext ctx) {}
}
This time, in the start() method, instead of storing the Greeting implementation as
a singleton, you use the provided bundle context to register it as a service in the ser-
vice registry. The first parameter you need to provide is the interface name(s) that the
service implements, followed by the actual service instance, and finally the service
properties. In the stop() method, you could unregister the service implementation
before stopping the bundle; but in practice, you don't need to do this. The OSG i
framework automatically unregisters any registered services when a bundle stops.
You've seen how to register a service, but what about discovering a service? The fol-
lowing listing shows a simplistic client that doesn't handle missing services and that
suffers from potential race conditions. We'll discuss a more robust way to access ser-
vices in chapter 4.
Listing 1.7 OSGi bundle activator with service discovery
package org.foo.hello.client;
import org.foo.hello.Greeting;
import org.osgi.framework.*;
public class Client implements BundleActivator {
B
Looks
up service
reference
public void start(BundleContext ctx) {
ServiceReference ref =
ctx.getServiceReference(Greeting.class.getName());
Retrieves and
uses service
((Greeting) ctx.getService(ref)).sayHello();
}
C
public void stop(BundleContext ctx) {}
}
Notice that accessing a service in OSG i is a two-step process. First, an indirect refer-
ence is retrieved from the service registry B . Second, this indirect reference is used to
 
Search WWH ::




Custom Search