javaosgiequinox

Should I prefer Dynamic-Import over Require-Bundle?


Should I prefer Dynamic-Import over Require-Bundle? The situation is that my OSGi bundle imports in Java code net.sf.ehcache package classes and references few other classes using configuration files. After I have noticed the errors/exceptions, I solved the issue of missing classes by changing from Import-Package: net.sf.ehcache to Require-Bundle: net.sf.ehcache. But I am wondering if I should have maybe added Dynamic-Import: net.sf.ehcache.* in addition to the Import-Package: net.sf.ehcache?


Solution

  • OSGi was designed to use Import-Package. If you have problems with Import-Package, you, or the bundles you use, likely have deeper problems with modularity. Import/Export Package provides the most flexible, least error prone model.

    The first thing I would advice is to use bnd to diagnose what is wrong with your setup, it sounds like you are writing the manifest manually? If this is the case, I can assure you there will be lots of problems in your future. Using bnd (my favorite is the workspace model, but you can use it in Gradle, Maven, and from the command line) will make OSGi is a breeze to use. You should not have to find the problems in the runtime, bnd should point them out to you in advance.

    The reason OSGi has Require-Bundle is because Eclipse sadly insisted on it since it resembled their existing modularity solution in 2005. Require-Bundle imports the exported packages from the required bundle. Although this is a widely spread model, the problem is that it is very sensitive to changes in the required model. If anything is refactored, you need to do a lot of work. Package imports/exports provide a looser coupling. Especially if you make sure that those exported packages only contain API.

    If Dynamic imports solve your problem, you're likely better off not using OSGi since it throws modularity under the bus. You paid all that money for the framework and bundles and then you basically do the class path thing: take the first thing that looks like what you're looking for. Most of the benefits of OSGi will disappear like snow for the sun.