【问题标题】:Access resources in another osgi bundle?访问另一个 osgi 包中的资源?
【发布时间】:2011-04-01 04:19:56
【问题描述】:

我使用 eclipse 插件项目向导(使用 eclipse Helios)创建了两个 OSGI 包 A 和 B。

在包 B 的清单文件中,我添加了包 A 作为依赖项。此外,我已经导出了 A 中的包,因此它们对 B 可见。我在包 A 中还有一个 .properties 文件,我想让包 B 可见。在包 AI 的 build.properties 窗格中指定:

source.. = src/
bin.includes = META-INF/,\
               .,\
               bundle_A.properties

现在在捆绑包 B 中,我尝试使用以下方法加载 .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;
  }

但这会产生空指针异常(在类路径中找不到该文件)。

是否可以从包 A 导出资源(就像导出包时一样)或以其他方式从 B 访问 A 中的文件(从包 B 访问包 A 的类加载器)?

【问题讨论】:

    标签: java eclipse osgi bundle


    【解决方案1】:

    试试/;如果你不输入/,类加载器会尝试从同一个包中加载资源。

    this.getClass().getClassLoader().getResourceAsStream( "/bundle_A.properties")
    

    【讨论】:

    • 这是错误的。它仍然只会使用 bundle B 的类加载器来查找对 bundle B 的类加载器不可见的资源/
    【解决方案2】:

    Bundle 上的 getEntry(String) 方法用于此目的。您可以使用它从任何捆绑包中加载任何资源。如果您不知道包内资源的确切路径,请参阅方法 findEntries()getEntryPaths()

    无需获取捆绑包的类加载器即可执行此操作。

    【讨论】:

    • 另请注意,不需要从 bundle A 中导出包含资源的包。
    【解决方案3】:

    如果您正在编写 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();
    

    【讨论】:

    • 这在 Helios 中显然已被弃用。
    【解决方案4】:

    您是否尝试过使用 bundle A 的 BundleContext 来加载资源?

    【讨论】:

    • Jep 并且工作正常,我只是很困惑为什么不能使用例如 this.getClass().getClassLoader().getResourceAsStream("bundle_A.properties") 从另一个包加载资源;当捆绑包被指定为依赖项并且 .properties 文件位于导出的包中时。
    • 因为 'this' 在捆绑包 A 中。使用捆绑包 B 中的类并且它可以工作。
    【解决方案5】:

    您是否考虑过添加一个方法来捆绑 A 的加载和返回资源的 API?

    许多人可能认为这是一个更好的设计,因为它允许更改资源的名称或存储方式,而不会破坏捆绑包 A 的客户端。

    【讨论】:

    • 这种方法在我运行插件测试时有效。但是当我通过启动配置运行包时,找不到 .properties 文件。设置 pluign-test 和 OSGI 运行配置有什么区别?
    猜你喜欢
    • 2016-07-22
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2017-06-08
    • 2013-12-07
    • 2011-11-25
    相关资源
    最近更新 更多