Search code examples
javamavenosgiapache-felix

What is the difference between OSGI Architecture and Maven multi module project?


I am trying to understand OSGI, as per definition it says

OSGi technology is a set of specifications that define a dynamic component system for Java. These specifications enable a development model where an application is composed of several components which are packaged in bundles. Components communicate locally and across the network through services.

But I am confused here as the same dynamic module creation can be done with Maven multi module project structure too. So my question is how OSGI architecture is different from Maven multi module projects.


Solution

  • The main difference between maven and OSGi is how modules depend on each other.

    In maven a module depends on a list of other maven modules. This is a simple model but often leads into problems in transitive dependencies. If the same module appears in the dependency tree with different versions maven simply chooses the highest version. This is a good guess but does not always work. Another typical case is having two modules with the same packages but different names (split packages).

    In OSGi dependencies are expressed as requirements and capabilities. The OSGi resolver is then used at assembly time of your application to find a closure over the candidate bundles (repository) that satisfy a set of initial requirements. Most commonly these initial reuirements are your top level user bundles. The resolver then determines a closure over the bundles that solves the requiremnts. So the obvious advantage is that when using the resolver you have a high confidence that the set of bundles you run will actually work. In plain java you simply run some jars together and hope for the best.

    The most common requirement is on a package in a version range. Another bundle may offer the package in a suitable version. It is then a candidate for the resolver.

    Luckily at build time creating bundles from maven builds is easy. You use the bnd-maven-plugin or maven-bundle-plugin. It typically figures out the requirements and capabilities on its own.

    In OSGi you always try to develop against APIs (API-jars) instead of runtime jars. This makes your code more loosely coupled.

    At assembly time in OSGi you need to provide a set of bundles to form the repository for the resolver to work on. This is often done using a pom. So actually this is not too different from plain maven. The main difference is that the resolver gives you a validates minimal set of bundles to run while a typical mavne build simply gives you a set of jars that represent all transitive dependencies.

    As an example see the new enroute microservice example. It shows how to create the individual bundles and how to assemble them into a running application. See also the tutorial for the example.