Java Reference
In-Depth Information
OSGI BUNDLES—MODULAR BUILDING BLOCKS
Bundles
are
Java modules
. On one level, a bundle is an ordinary
JAR
file, with some
extra headers and metadata in its
JAR
manifest. The
OSG
i runtime is usually referred
to as the “
OSG
i framework,” or sometimes “the framework,” and is a container that
manages the lifecycle and operation of
OSG
i bundles. Outside of an
OSG
i framework,
a bundle behaves like any other
JAR
, with all the same disadvantages and no improve-
ment to modularity. Inside an
OSG
i framework, a bundle behaves differently. The
classes inside an
OSG
i bundle are able to use one another like any other
JAR
in stan-
dard Java, but the
OSG
i framework prevents classes inside a bundle from being able to
access classes inside any other bundle unless they're explicitly allowed to do so. One
way of thinking about this is that it acts like a new visibility modifier for classes, with a
scope between protected and public, allowing the classes to be accessed only by other
code packaged in the same
JAR
file.
Obviously, if
JAR
files weren't able to load any classes from one another they would
be fairly useless, which is why in
OSG
i a bundle has the ability to deliberately expose
packages outside itself for use by other bundles. The other half of the modularity
statement is that, in order to make use of an “exported” package, a bundle must
define an “import” for it. In combination, these imports and exports provide a strict
definition of the classes that can be shared between
OSG
i bundles, but express it in an
extremely simple way.
Listing 1.1
A simple bundle manifest that imports and exports packages
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-SymbolicName: fancyfoods.example
Bundle-Version: 1.0.0
Bundle-Name: Fancy Foods example manifest
Import-Package: fancyfoods.api.pkg;version="[1.0.0,2.0.0)"
Export-Package: fancyfoods.example.pkg;version="1.0.0"
Many more possible headers can be used in
OSG
i, a number of which are described in
later chapters.
By strictly describing the links between modules,
OSG
i allows Java programs to be
less like minestrone and more like a tray of cupcakes (figure 1.4). Each cupcake has
an internal structure (cake, paper case, icing, and perhaps decorations), but is com-
pletely separate from the other cupcakes. Importantly, a chocolate cupcake can be
removed and replaced with a lemon cupcake without affecting the whole tray. As you
build relationships between
OSG
i bundles, this becomes like stacking the cupcakes on
top of one another. Exporting a package provides a platform onto which an
import
can
be added. As you build up a stack of cupcakes, the cupcakes in the higher layers will
be resting on other cupcakes in lower levels, but these dependencies can be easily
identified. This prevents you from accidentally removing the cupcake on the bottom
and causing an avalanche!