java - 将资源文件添加到 karaf 类路径

标签 java osgi classpath apache-karaf blueprint-osgi

我正在使用 karaf 4.0.5 和 osgi 开发一个项目。我们有调用 REST API 的客户端代码,这需要加载 3 个“*.properties”文件。我得到了一个客户端 jar,我用它来调用服务器端类和方法(包含我无法更新的代码)。所需的属性文件存在于提供的客户端 jar 中,但它们的代码仍然无法找到并加载它们。

在调试我的 pax 考试时,我发现它没有从 jar 加载资源文件的以下可能原因。

  1. 加载文件的代码似乎试图仅从 Bundle Classloader 加载资源,并且
  2. 它调用“getResource()”方法而不是“getResourceAsStream()”方法。

或者,我尝试将资源添加到我的文件系统上的一个目录,并在类路径中附加目录的位置,如下所示:

-cp .;C:/Users/abcUser/Desktop/resourceFolder/;

(Windows 7,在使用 eclipse 中的 junit 4+ 执行 pax 考试时,类路径条目添加为 VM 参数)-> 这也不起作用,它仍然无法找到这些文件。 我还有哪些其他选项可以让 Bundle Classloader 找到这些文件?

注意:我们已经有一堆其他 *.cfg 文件,它们的内容使用蓝图加载到 bean 中并在容器中注册,但这不是我需要在这里做的。在运行时,这些文件应该可供 BundleClassloader 使用,并且应该通过“getResource()”方法检索。

更新:根据已接受答案的以下部分,应用程序已成功加载属性文件。

Another thing to check is whether the client code is actually using the bundle classloader when trying to load these resources. In some cases the code tries to be clever by using the Thread Context Classloader, which would need to be set appropriately before calling the client code.

来自客户端 jar 的代码与猜测的完全一样:资源加载是使用 Thread.currentThread().getContextClassLoader() 进行的。我能够将 ContextLoader 设置为 CustomAbstractProcessor 的类加载器,它现在从该包的类路径加载属性文件!

ClassLoader previousCL = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(CustomAbstractProcessor.class.getClassLoader());
try {
    //REST call to server using classes and methods from provided client jar.
}
finally {
    Thread.currentThread().setContextClassLoader(previousCL);
}

最佳答案

I have been given a client jar that I'm using to invoke the server side classes and methods (containing code that I cannot update). The required property files are present in the provided client jar, but their code still doesn't locate and load them.

如果此客户端 jar 作为 OSGi 包运行,那么当(且仅当)资源位于包的类路径中时,它应该能够使用自己的类加载器(包类加载器)查找资源。

OSGi 包的默认类路径是 . 即包的根目录。这可以使用 Bundle-ClassPath list header 覆盖,并用于包中的一个或多个位置。

  • 一种可能是客户端包具有不同的类路径集,并且属性文件不在其中。
  • 另一种可能性是属性文件位于类路径中,但位置与预期不符,例如代码正在寻找 foo.properties 并且文件位于 `/props/foo.properties'

it calls the getResource() method instead of the getResourceAsStream() method.

getResourceAsStream() 只是 getResource().openStream() 的空安全版本。

What other options do I have so the Bundle Classloader locates these files?

要检查的另一件事是客户端代码在尝试加载这些资源时是否实际使用了捆绑类加载器。在某些情况下,代码试图通过使用线程上下文类加载器来变得更聪明,这需要在调用客户端代码之前进行适当的设置。

关于java - 将资源文件添加到 karaf 类路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46800863/

相关文章:

java - 在 centOS Linux Box 中运行的 Spring Java Mail 程序抛出异常

java - 在 Pod 意外关闭时运行退出逻辑的最佳方法

java - 偶数、奇数和偶数消费者-生产者

spring - 在 JAR 中使用 PathMatchingResourcePatternResolver 和 URLClassloader 查找资源

java - 从类路径目录中获取资源列表

java - JGroups 未找到或加载主类

java - 在没有 BouncyCaSTLe 的情况下以编程方式为 SSL Client-Auth 创建客户端证书的任何方法?

spring - 如何在 Spring DM 中获得 BundleContext?

java - NoClassDefFoundError : com/sun/xml/internal/bind/DatatypeConverterImpl using knopfletfish

java - mangen 将 'Bundle-ManifestVersion: 1' 添加到 list 中,但 felix 似乎不接受值 1