简体   繁体   English

运行 JAR 时将外部资源加载到类路径中

[英]Load external resource into classpath when running JAR

I have an application that requires configuration on start-up.我有一个需要在启动时进行配置的应用程序。 However, I can't store this in /resources since every environment that will host this application will be completely different.但是,我不能将其存储在 /resources 中,因为托管此应用程序的每个环境都将完全不同。 I want to put this under a directory found via a system property defined in the environment, but for now I want to get an absolute path working - let's say /tr/apps/myFile.txt (where /tr/apps/ is the root of where the application is deployed).我想把它放在通过环境中定义的系统属性找到的目录下,但现在我想让绝对路径工作 - 比如说/tr/apps/myFile.txt (其中 /tr/apps/ 是根应用程序的部署位置)。

I found a Maven plugin which looked like it would do the job: https://maven.apache.org/surefire/maven-surefire-plugin/examples/configuring-classpath.html I found a Maven plugin which looked like it would do the job: https://maven.apache.org/surefire/maven-surefire-plugin/examples/configuring-classpath.html

So I added this to my pom:所以我把这个添加到我的 pom 中:

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M3</version>
        <configuration>
          <additionalClasspathElements>
            <additionalClasspathElement>/tr/apps</additionalClasspathElement>
          </additionalClasspathElements>
        </configuration>
      </plugin>
    </plugins>
  </build>

Now I have to use the following method to get the file:现在我必须使用以下方法来获取文件:

InputStream inputStream = Thread.currentThread().getContextClassloader().getResourceAsStream("tr/apps/myFile.txt")
if(inputStream == null) {
    throw new Exception("myFile.txt not found");
}

This exception always seems to be thrown (ie it isn't able to find the file on the classpath).这个异常似乎总是被抛出(即它无法在类路径中找到文件)。 Does anybody know why this is?有人知道这是为什么吗? Or if there is an alternative plugin/solution for this?或者是否有替代插件/解决方案?

Would really appreciate any input!非常感谢任何输入!

Did you try looking for the answer in Stackoverflow?您是否尝试在 Stackoverflow 中寻找答案? It is a common question in Java and the answer is always quite simple (in the end depending even if you are using spring or not).这是 Java 中的一个常见问题,答案总是很简单(最终取决于您是否使用 spring)。

Try with the solution described here How a JAR file can read an external properties file尝试使用此处描述的解决方案JAR 文件如何读取外部属性文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM