将资源在运行时放置在类路径上

huangapple go评论112阅读模式
英文:

Put resource on classpath at runtime

问题

我需要在我的应用程序中创建一个 org.apache.camel.guice.Main 的实例。出于我不想深入讨论的原因,我不能在我的jar/bundle中打包一个 jndi.properties 文件,该文件将被 org.apache.camel.guice.Main.run() 使用以引导该应用程序。我也不能向文件系统写入任何内容。

我确实拥有通常作为Java对象、字符串映射的映射在运行时可用的 jndi.properties 属性。我能否将这些属性写入一个“动态”的 jndi.properties 文件,并将其放在类路径中(或将其作为“资源”添加到类加载器中)?类似这样:

this.getClass().putResourceAsStream(properties);

这样,那些需要通过 getResource() 或 getResourceAsStream() 进行加载的第三方框架能够做到这一点吗?

英文:

I need to create an instance of org.apache.camel.guice.Main in my application. For reasons I don't want to get into, I cannot package a jndi.properties file in my jar/bundle, which will be used by org.apache.camel.guice.Main.run() to bootstrap the app. I also cannot write anything to the file system.

I do have the properties that would normally go into jndi.properties available at runtime as a java object, map of strings, whatver. Can I write these out to a "dynamic" jndi.properties and put it on the classpath (or add it to a classloader as a "resource")? Something like:

this.getClass().putResourceAsStream(properties);

So that 3rd party frameworks that do need to load via getResource() or getResourceAsStream() can do it?

答案1

得分: 0

我通过以下4个步骤成功实现了这个:

  1. 在InitialContext中使用接受java.util.Properties参数的构造函数来创建上下文。
  2. 在Activator中使用一个方法来确保我的应用程序捆绑包使用捆绑包上下文类加载器,而不是线程上下文类加载器。
  3. 在头部中除了使用package-imports外还要使用require bundle。
  4. 使用org.apache.camel.guice.Main.run()来启动camel。

特别感谢评论中的Thorbjorn Andersen,他让我回过头来仔细看了InitialContext的API。

英文:

I was able to get this to work by doing 4 things:

  1. Using the constructor in InitialContext that takes
    java.util.Properties as an argument to create the context
  2. Using a hack in Activator to make sure my application bundle is using bundle context classloader, not the thread context classloader
  3. Use require bundle in addition to package-imports in the header.
  4. Using org.apache.camel.guice.Main.run() to start camel

Big thanks to Thorbjorn Andersen in the comments, that made me go back and take a closer look at the InitialContext api.

huangapple
  • 本文由 发表于 2020年4月7日 06:13:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/61069788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定