What is the Service Registry in OSGi?

What is the Service Registry in OSGi?

The OSGi Service Registry is a centralized, dynamic registry that enables bundles (modules) to register, discover, and use services at runtime. It acts as a mediator between service providers and consumers, enabling loosely coupled, dynamic communication in an OSGi-based application.


Key Features of the OSGi Service Registry

* Decoupling – Service providers and consumers do not need direct dependencies.
* Dynamic Registration & Discovery – Services can be registered and found at runtime.
* Versioning & Filtering – Supports different versions and custom filtering.
* Dependency Management – Ensures services are available before usage.


How the Service Registry Works :
1. Registering a Service (Provider)

A bundle can register a service in the Service Registry.

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

public class MyActivator implements BundleActivator {
    private ServiceRegistration<?> registration;

    @Override
    public void start(BundleContext context) {
        MyService myService = new MyServiceImpl();
        registration = context.registerService(MyService.class.getName(), myService, null);
        System.out.println("Service Registered!");
    }

    @Override
    public void stop(BundleContext context) {
        registration.unregister();
        System.out.println("Service Unregistered!");
    }
}

* Here, registerService() adds the service to the Service Registry.


2. Consuming a Service (Client)

Another bundle can retrieve and use the service.

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

public class ClientActivator implements BundleActivator {
    @Override
    public void start(BundleContext context) {
        ServiceReference<?> reference = context.getServiceReference(MyService.class.getName());
        if (reference != null) {
            MyService myService = (MyService) context.getService(reference);
            myService.execute();
        }
    }

    @Override
    public void stop(BundleContext context) {
        System.out.println("Client Stopped!");
    }
}

* Here, getServiceReference() finds the service in the Service Registry.


Advantages of the OSGi Service Registry

* Loose Coupling – Services are discovered dynamically rather than hardcoded.
* Hot Deployment – Services can be added/removed at runtime without restarting.
* Better Maintainability – Decoupled architecture makes updates easier.
* Versioning Support – Supports multiple versions of the same service.