concept service implementation in category osgi

appears as: service implementation, service implementations, service implementation, service implementations
OSGi in Depth

This is an excerpt from Manning's book OSGi in Depth.

A service consists of an interface and an implementation. The service consumer only sees and uses the service interfaces, whereas the service provider supplies the service implementations and doesn’t interact directly with the consumers.

In these roles, the OSGi service registry acts as the mediator, isolating the provider from the requestor. The service provider bundle owns the service interface, service properties, and service implementation. The service requestor bundle uses the service interface and service properties, but it can’t access the service implementation. A diagram of the OSGi service registry is shown in figure 2.8.

Figure 2.8. The service provider bundle registers the service interface, service properties, and service implementation into the OSGi service registry. The service requestor bundle retrieves the service interface and the service properties from the OSGi service registry.

The Printer service interface is defined by a Java interface with a single println method. No implementation is needed to define the service interface. Technically, we could use a Java class rather than a Java interface to define the OSGi service interface. In this case, the service implementation would extend the Java class instead of implementing the Java interface. But using a Java interface is cleaner, is easier to understand, and keeps coupling between the service provider and the service requestor to a minimum.

Next, we need a Java object to serve as the service implementation. Version 1.3 of the Printer class is almost good enough; we just need to change it so that it implements the service interface, as shown here.

Listing 2.6. Upgraded Printer service implementation
package manning.osgi.helloworld.impl; import java.text.DateFormat; import java.util.Date; import manning.osgi.helloworld.Printer; public class PrinterImpl implements Printer { private static final String SEPARATOR = ": "; public void print(String message) { System.out.println(getCurrentTime() + SEPARATOR + message); } private String getCurrentTime() { return DateFormat.getTimeInstance(DateFormat.LONG). format(new Date()); } }

First, the service implementation must implement (or extend) the service interface. Second, it’s important to use a different Java package for the implementation than what is used for the interface. The package used by the interface needs to be exported, whereas we don’t want to export the package used by the implementation. Otherwise, we might not be able to change the implementation easily without reinstalling the clients.