Declarative Services in Apache Karaf

In this post I would like to demonstrate how easy it is to use Declarative Services in Karaf. The source code will be based on the Converter service and client that were used in a previous example about remote services. This time however both the service and the client will reside in the same OSGi container and instead of Activators Declarative Services will be used. The source code of this example is available in GitHub. The following projects are implemented:

converter (interface of a conversion service - same as in previous example)

converter-impl (implementation of conversion service using DS)

converter-client (client of conversion service using DS)

converter-ds-feature (maven host project for converter ds feature)

Converter Service

The converter interface is exact same as in the previous example not using Declarative Services. It simply provides the interface of the service. The service implementation however is modified. We no longer need the Activator. The ServiceImpl class is the only thing needed. In addition to the Interface implementations methods, two more methods are added:

These methods are called for the Declarative Services runtime, when the service is activated and de-activated. In this simple scenario they do nothig but printing a message. In order for the DS runtime to work, we need to add a service component file. This file is declared in the MANIFEST.MF. In our case we modify the pom.xml to make the appropriate line appear in the manifest file:

In this file we define which service we want to look up. We search for services based on interfaces and not concrete implementations. We also define which methods to call, when the service is set and unset by the DS runtime. This methods are implemented by our class:

Notice that when we start the service nothing happens. The activate method isn't called. This method isn't a replacement of the Activator's start method. It isn't called, when the bundle is started. It is called by the DS runtime, when it is needed to. This only happens, when a client with a reference to this service is started. So, everything happens when the client is started. Notice the sequence of the print-out messages. First the service activate method is called. Then the set and the activate method of the client follow. When we stop the client, both the client and the service are de-activated. Of course the service wouldn't be de-activated, if there was a reference to it from another bundle.