转载来自:http://blog.csdn.net/qimiguang/article/details/21371495
最近在做一个“把OSIG上的bundle结构的工程打成标准的war包来在各中间件上发布”的工作,给了自己一个了解OSGI底层源码的机会。过程中也发现了许多之前开发时没注意的小问题,譬如这个Dependencise中的Required Plug-ins和Imported Packages的区别,网上搜集了些资料,总结到这里吧:
参考自:http://blog.sina.com.cn/s/blog_69d0d3310100mehz.html
Required-Bundle: Specifythe list of plug-ins required for the operation of this plug-in.
Imported-Package:Specifypackages on which this plug-in depends without explicitly identifying theiroriginating plug-in.
Eclipse allows to define dependencies between plug-ins based on bundle or on package level. In theMANIFEST.MFof the plugin.xml you can tell that your plug-in should either depend onanother plug-in (and all its exported packages) or if your plug-in should onlydepend on the availability of certain packages no matter which plug-in isexporting this package.
The corresponding statements inMANIFEST.MF are Require-Bundle: or Import-Package:
Today I got the question what approach should bepreferred.
I believe the preferred way should be to useImport-Package because the coupling between the plug-ins is not that tight. Asonly as one plug-in exports this package the other plug-in will be fine. Withthis you can replaced a plug-in without changing the other plug-ins.
Of course if you have the same package in different plug-ins then you have to use the plug-in dependency.
The other advantage of plug-in dependencies isthat the dependency is very clearly explicit, with the import-package it is notimmediately obvious which plug-in is contributing this package.
But in total I would argue that loose coupling isalways better so in general import-package should be preferred.
其实这段E文已经说的很清晰了。再摘抄一段中文注解吧:
参考自:http://www.xeclipse.com/?p=1195(其中部分观点我认为有误)
理解OSGI的Package import-export机制的关键在于明白每个bundle都有自己的Class Loader。
对于OSGI环境来说,它们是没有区别的。无论是Require-Bundle还是Imported-Package,前提都是需要把相关的packages先Export出。
它们之间,仅仅只是依赖的颗粒度的区别。Required-Bundle依赖的是精确指定版本的bundle,而Import-Package依赖的是package,它会根据class loader的顺序选择最先找到的class,而不关心是哪一个bundle export出来的。
对于同一个package被许多不同的bundle同时export的时候,优先考虑使用required bundle(这跟网上流传的优先使用imported package不同,我个人认为使用imported package有误)。当依赖的多个piug-in同时export了相同的package时,根据依赖中的顺序,优先使用顺序靠前的bundle中的package。这里的顺序是指如下图:
2.0.0先与1.0.0被依赖甚至org.eclipse.jetty中也有相同的package时,因为org.eclipse.ui.thr.ole(2.0.0)最先被依赖,所以优先找它中的package