英文:
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个步骤成功实现了这个:
- 在InitialContext中使用接受java.util.Properties参数的构造函数来创建上下文。
- 在Activator中使用一个方法来确保我的应用程序捆绑包使用捆绑包上下文类加载器,而不是线程上下文类加载器。
- 在头部中除了使用package-imports外还要使用require bundle。
- 使用org.apache.camel.guice.Main.run()来启动camel。
特别感谢评论中的Thorbjorn Andersen,他让我回过头来仔细看了InitialContext的API。
英文:
I was able to get this to work by doing 4 things:
- Using the constructor in InitialContext that takes
java.util.Properties as an argument to create the context - Using a hack in Activator to make sure my application bundle is using bundle context classloader, not the thread context classloader
- Use require bundle in addition to package-imports in the header.
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论