4.6 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.

Ensure the server instance is stopped 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. (This is found under the src/main/resources directory.) 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 successfully, open a web browser and navigate to http://localhost:8080/greenpages. On the home page type wilkinson into the search field and press Submit. This will return a list (of size 1) of search results. From here, select view to get the “detailed” listing.

This uses the stub implementation of the Directory interface (DirectoryImpl) which only knows about “Andy Wilkinson”.

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