Time for action - removing lookups in the service implementation

We will now update the service implementation, as we want to remove the dependency on the core OSGi framework classes for the lookup of the inventory and declare it as a field for injection.

As a reminder, the BookshelfServiceImpl currently starts like this:

public class BookshelfServiceImpl implements BookshelfService
{
private String sessionId;
BundleContext context;
public BookshelfServiceImpl(BundleContext context)
{
this.context = context;
}
private BookInventory lookupBookInventory()
{
ServiceReference ref = this.context.getServiceReference(
BookInventory.class.getName());
if (ref == null)
{
throw new BookInventoryNotRegisteredRuntimeException(
BookInventory.class.getName());
}
return (BookInventory) this.context.getService(ref);
}

And continues with its methods that call lookupBookInventory() when they need access to the currently registered inventory implementation.

We will declare the inventory field, which will be injected with the registered BookInventory implementation:

public class BookshelfServiceImpl implements BookshelfService
{
String session;
BookInventory inventory;

To avoid modifying the whole class and replacing calls to lookupBookInventory() with this.inventory, we'll update the method to return it.

private BookInventory lookupBookInventory()
{
return this.inventory;
}

The BundleContext is no longer required. We can remove the context property and update the constructor to take no parameters:

public BookshelfServiceImpl()
{
}

The following OSGi framework imports are also no longer needed and can be removed.

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

This class is now a POJO that's also container-independent; although it needs a container and service injection to make it functional, it does not specifically need to know how this is going to be achieved. This is one of the most attractive features of dependency injection.

For example, this same bundle can be used in another container, such as Spring, Tapestry, or PicoContainer with the appropriate injection configuration.

Note

Some dependency injection frameworks require a setter (or a constructor parameter) to be declared for fields that need to be injected.

With these changes, the activator for this bundle fails to compile. This is because it constructs a BookshelfServiceImpl passing a BundleContext. There's no need to fix it, as it is going to be deleted.

Now, let's write the iPOJO configuration for this bundle.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.136.119