Java Reference
In-Depth Information
start 3
This will start the bundle and ready it for use by other bundles.
Using the Service in a Client Bundle
Using the service is almost exactly the same as creating the service, except that we need to specify our
dependence on the service in the bundle. Let's first review the client-side Java code. In this case, we
simply look up the service and demo it in the Activator for the client bundle. This is simple, and to the
point, though not necessarily typical. In the source code for the book, this is a different Maven project,
called
helloworld-client
.
package com.apress.springenterpriserecipes.osgi.helloworld.client;
import com.apress.springenterpriserecipes.osgi.helloworld.service.GreeterService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import java.util.Arrays;
import java.util.Locale;
public class Activator implements BundleActivator {
public void start(BundleContext bundleContext) throws Exception {
ServiceReference refs[] = bundleContext.getServiceReferences(
GreeterService.class.getName(), null);
if (null == refs || refs.length == 0) {
System.out.println("there is no service by this description!");
return;
}
GreeterService greeterService = (GreeterService)
bundleContext.getService(refs[0]);
String[] names = {"Gary", "Steve", "Josh", "Mario",
➥
"Srinivas", "Tom", "James", "Manuel"};
for (String language : Arrays.asList(
Locale.ENGLISH.toString(),
Locale.FRENCH.toString(),
Locale.ITALIAN.toString())) {
for (String name : names) {
System.out.println(greeterService.greet(language, name));
}
}
}
public void stop(BundleContext bundleContext) throws Exception {
// NOOP
}
}
The salient code is in bold. Here, we look up a
ServiceReference
in the OSGi registry. We use the
same name as we provided when we registered the class in the registry. The second argument,
null
, is
Search WWH ::
Custom Search