What is a Fragment Bundle in OSGi?

What is a Fragment Bundle in OSGi?

An OSGi Fragment Bundle is a special type of OSGi bundle that does not have its own classloader and cannot be started, stopped, or managed like a normal bundle. Instead, it attaches to a host bundle at runtime and extends its functionality.


Key Characteristics of a Fragment Bundle

* No Lifecycle – Fragment bundles do not have BundleActivator or lifecycle states (e.g., STARTING, ACTIVE).
* Attaches to a Host Bundle – The fragment is merged into the host bundle at runtime.
* Shares the Same Classloader – A fragment’s classes, resources, and dependencies are accessible from the host bundle.
* Cannot Be Installed/Started Independently – It must always attach to a host bundle.


Use Cases for Fragment Bundles

* Adding Extra Resources – Useful for providing additional configuration files, images, or translations.
* Patching Existing Bundles – Enables modifying or extending an existing bundle without changing its core code.
* Providing Platform-Specific Implementations – For example, different fragments for Windows, Linux, and macOS.
* Extending Functionality – Adding additional libraries or classes to a host bundle.


Example: Creating a Fragment Bundle
1. MANIFEST.MF (Fragment Bundle)
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: My Fragment Bundle
Bundle-SymbolicName: com.example.fragment
Bundle-Version: 1.0.0
Fragment-Host: com.example.hostbundle  # Specifies the host bundle

* The Fragment-Host header specifies the bundle to which the fragment will attach.

2. How the Fragment Works
  • The fragment bundle is installed separately, but it is attached automatically to the specified host bundle.
  • The host bundle can now access all classes and resources from the fragment bundle.

Differences Between a Regular Bundle and a Fragment Bundle
Feature Regular Bundle Fragment Bundle
Lifecycle Has STARTING, ACTIVE, etc. No lifecycle (merged into host)
Classloader Has its own classloader Uses host bundle’s classloader
Standalone Execution Can start and stop independently Must be attached to a host bundle
Use Case Implements full functionality Provides additional resources or patches