logo
OSGi Framework - Interview Questions and Answers
What is an OSGi bundle?
What is an OSGi Bundle?

An OSGi bundle is a self-contained, reusable module in an OSGi-based application. It is essentially a JAR file with additional metadata in its META-INF/MANIFEST.MF file, which defines dependencies, versioning, and lifecycle instructions.

Each bundle has its own classloader and can dynamically interact with other bundles through the OSGi Service Registry.


Structure of an OSGi Bundle

An OSGi bundle follows a specific structure inside a JAR file:

my-bundle.jar
??? META-INF/
?   ??? MANIFEST.MF   (Contains OSGi metadata)
??? com/example/
?   ??? MyService.class  (Java class)
?   ??? MyServiceImpl.class
??? resources/
Example: A Simple MANIFEST.MF File

This file is crucial in an OSGi bundle and defines its properties:

Bundle-Name: My OSGi Bundle
Bundle-SymbolicName: com.example.mybundle
Bundle-Version: 1.0.0
Bundle-Activator: com.example.MyActivator
Import-Package: org.osgi.framework
Export-Package: com.example.api

Lifecycle of an OSGi Bundle

Each OSGi bundle has a well-defined lifecycle, managed by the OSGi framework:

  1. INSTALLED – The bundle is installed but not yet started.
  2. RESOLVED – The bundle's dependencies are resolved.
  3. STARTING – The bundle is in the process of starting.
  4. ACTIVE – The bundle is running and providing services.
  5. STOPPING – The bundle is stopping its execution.
  6. UNINSTALLED – The bundle is removed from the system.

Creating an OSGi Bundle
Step 1: Implement a Bundle Activator

To manage a bundle’s lifecycle, you can create a Bundle Activator class:

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

public class MyActivator implements BundleActivator {
    @Override
    public void start(BundleContext context) {
        System.out.println("Bundle Started!");
    }

    @Override
    public void stop(BundleContext context) {
        System.out.println("Bundle Stopped!");
    }
}
Step 2: Package as a JAR
  1. Compile your classes.
  2. Create a META-INF/MANIFEST.MF file with OSGi metadata.
  3. Package everything into a JAR file.

Why Use OSGi Bundles?

* Modularization – Bundles enable better code organization.
* Dynamic Updates – Can be installed/uninstalled at runtime without restarting the application.
* Dependency Management – Avoids classloading conflicts.
* Reusability – Bundles can be reused across different applications.