What is the difference between “Import-Bundle” and

2020-06-09 04:24发布

问题:

What is the difference between spring source dm server specific Import-Bundle and OSGi's Require-Bundle?
I am confused whether to use Import-Bundle or Require-Bundle in my project.

回答1:

Import-Bundle is similar to Require-Bundle, it creates a complete dependency on the other bundle, including that bundle's dependencies. This transitivity is bad because you have no idea what you depend, creating the infamous "big ball of mud" problem we're so familiar with in Object oriented programming.

In OO, we've found a solution to this entanglement by using interfaces, they separate implementation from specification. OSGi is built around a similar albeit of an higher order concept of service contracts. These contracts (interfaces, permissions, helper classes) are stored in a package. In contract based programming you depend on the contracts, not the implementations. Ergo, an OSGi bundle should depend on packages since they represent the contracts.

 Import-Package               <=> interface
 Import-Bundle/Require-Bundle <=> implementation class

Import-Bundle is NOT OSGi, it is a proprietary Spring extension. It is a cleaner form for Require-Bundle; the uncleanliness was necessary to support some Eclipse use cases. The OSGi decided not to adopt this header since the Require-Bundle/Import-Bundle is fundamentally broken if you want to build systems from components.



回答2:

Ideally you should try to rather use Import-Package instead. It makes you bundles less dependent on each other. It also allows to show that you only depend on a part of a bundle. This is also important for managing versions. In OSGi you can define the versions of exported packages independent of the bundle version. So you can make sure you only change versions of an API if it really changes. This can make your app much more manageable.



回答3:

It's explained here at SpringSource

So summarizing: Import-Bundle will import all exported packages of a certain bundle, it will resolve that when deploying, while Require-Bundle really requires a bundle with that type, and that relationship stays that way during runtime.

Normally they would behave pretty much the same. For example it can be different when:

  • You have 'split packages': packages that exist in multiple bundles, you might 'lose' dependencies with Import-Package / Import-Bundle that you can only express with Require-Bundle (Note that you really should avoid split packages if you can)

  • I think the Bundle->Package resolution is when you deploy that bundle. If you redeploy the bundle with the exported bundles to a version with different export, I don't think the bundle will notice. To be honest I'm not exactly sure about this one.

All in all, I'd say stick with the OSGi standard: Import-Package or Require-Bundle if you really need it. You'll have a bit more headers but you'll so many more options in the long run.