访问另一个osgi包中的资源?
我使用eclipse Plug-in项目向导(使用eclipse Helios)创建了两个OSGI包A和B.
在bundle BI的清单文件中添加了bundle A作为依赖项。 此外,我已经在A中导出了包,因此它们对于B是可见的。我还在包A中有一个.properties文件,我希望它对包B可见。在包中的build.properties窗格中,AI指定了:
source.. = src/ bin.includes = META-INF/,\ .,\ bundle_A.properties
现在在BI中尝试使用以下命令加载.properties文件:
private Properties loadProperties() { Properties properties = new Properties(); InputStream istream = this.getClass().getClassLoader().getResourceAsStream( "bundle_A.properties"); try { properties.load(istream); } catch (IOException e) { logger.error("Properties file not found!", e); } return properties; }
但是这会产生一个nullpointerexception(在类路径中找不到该文件)。
是否可以从捆绑包A中导出资源(就像导出包时一样)或以某种方式以另一种方式从B访问A中的文件(从捆绑包B访问捆绑包A的类加载器)?
如果您正在编写Eclipse插件,可以尝试以下方法:
Bundle bundle = Platform.getBundle("your.plugin.id"); Path path = new Path("path/to/a/file.type"); URL fileURL = Platform.find(bundle, path); InputStream in = fileURL.openStream();
Bundle
上的getEntry(String)
方法用于此目的。 您可以使用它从任何捆绑包加载任何资源。 如果您不知道bundle中资源的确切路径,也请参阅findEntries()
和getEntryPaths()
方法。
没有必要抓住bundle的类加载器来执行此操作。
您是否考虑过添加一个方法来捆绑加载和返回资源的A的API?
许多人可能会认为这是一个更好的设计,因为它允许更改资源的名称或方式,而不会破坏捆绑包A的客户端。
您是否尝试使用捆绑包A的BundleContext来加载资源?
试试/
; 如果你不放/
,类加载器将尝试从同一个包加载资源。
this.getClass().getClassLoader().getResourceAsStream( "/bundle_A.properties")