4.7 Publishing an OSGi Service

At the end of the previous step, a dependency was created on an OSGi Service Registry exposed instance of greenpages.Directory. The application would not start because no other bundle was contributing an instance of this service to the Service Registry.

Stop the server instance before proceeding.

Add Implementation

In this step Spring’s context scanning is added which will create an instance of the DirectoryImpl class.

Open the greenpages.internal.DirectoryImpl class in the greenpages.app project. Add the @Component annotation to the class:

@Component("directory")
public class DirectoryImpl implements Directory {
…

generating imports with Eclipse’s help if necessary.

Open the META-INF/spring/module-context.xml in the greenpages.app project. Add component scanning to this file:

<context:component-scan base-package="greenpages.internal"/>

When complete, go to the next step.

Publish OSGi Service

In this step the DirectoryImpl instance is published to the OSGi Service Registry.

Open the META-INF/spring/osgi-context.xml file. Add the <osgi:service/> tag to publish the directory bean with an interface of greenpages.Directory.

<osgi:service ref="directory" interface="greenpages.Directory"/>

A Working Web Application

Start (or restart) the dm Server instance from the Servers view. If the GreenPages PAR was not removed before, it will be automatically deployed, otherwise deploy it as before. There should be no errors reported. When GreenPages is deployed succesfully, open a web browser and navigate to http://localhost:8080/greenpages/home.htm. On the home page type johnson into the search field and press Submit. Unlike the previous attempt, this should return a list (of size 1) of search results. From here, select view to get the “detailed” listing.

This uses a stub implementation of the Directory interface which only knows about “Rod Johnson”.

The web interface is complete enough. Go to the next chapter to see the middle tier implementation.