OSGi

OSGi (Open Services Gateway initiative) is a component platform for Java. An application is a set of bundles, each with a versioned manifest declaring which packages it exports and imports. Bundles find each other through a service registry and can be replaced at runtime without a restart.

Paradigm: Component-Oriented Programming

What Makes OSGi Special

  • Bundles are components. A bundle is a JAR with extra manifest headers: Bundle-SymbolicName, Export-Package and Import-Package with version ranges.
  • Strict encapsulation. Only exported packages are visible to other bundles. Everything else is private, which is enforced by class loaders, not by convention.
  • A dynamic service registry. Bundles publish objects under an interface and others look them up. Services can appear and disappear while the system is running.
  • Full lifecycle. Bundles are installed, resolved, started, stopped, updated and uninstalled independently, with several versions of one library side by side.
  • Declarative Services. Annotations such as @Component and @Reference let you wire components without touching the registry API.

Example: A service and a consumer in two components

// Bundle A exports com.example.greeter.api (Export-Package header)
package com.example.greeter.api;

public interface Greeter {
    String greet(String name);
}

// Bundle B provides the service
package com.example.greeter.impl;

import com.example.greeter.api.Greeter;
import org.osgi.service.component.annotations.Component;

@Component(service = Greeter.class)
public class FriendlyGreeter implements Greeter {
    public String greet(String name) { return "Hello, " + name; }
}

// Bundle C consumes it, knowing only the interface
package com.example.console;

import com.example.greeter.api.Greeter;
import org.osgi.service.component.annotations.*;

@Component
public class Console {
    @Reference Greeter greeter;

    @Activate
    void start() { System.out.println(greeter.greet("OSGi")); }
}

How It Works

  • The interface package is exported by one bundle. The implementation package is not exported, so no other bundle can depend on FriendlyGreeter directly.
  • @Component(service = Greeter.class) tells the runtime to register the class in the service registry under that interface.
  • Console declares a @Reference and is activated only when a Greeter is available. If the provider is stopped, Console is deactivated.
  • Replacing FriendlyGreeter with another implementation, even at runtime, changes the output without recompiling or restarting the consumer.

History and Where It Is Used

OSGi is the foundation of the Eclipse IDE, Apache Felix and Karaf, Adobe Experience Manager and many embedded and automotive systems. Modern Java projects often reach for the simpler Java module system (JPMS) or microservices, but OSGi remains the choice when modules must change at runtime.

Learn More