将外部配置添加到类路径,并使用getResourcesAsStream()

我有一个需要在启动时进行配置的应用程序。但是,我无法将其存储在/ resources中,因为承载此应用程序的每个环境都会完全不同。现在,我想将文件系统中的目录添加到类路径-假设 / tr / apps / (其中/ tr / apps /是应用程序部署的根目录)。>

我找到了一个看起来可以完成工作的Maven插件: https://maven.apache.org/surefire/maven-surefire-plugin/examples/configuring-classpath.html

因此我将此添加到了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>

现在,我已经使用以下方法来获取文件:

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

似乎总是抛出该异常(即,它无法在类路径上找到文件)。有人知道这是为什么吗?或是否有替代插件/解决方案?

非常感谢您的投入!

ding1988ding 回答:将外部配置添加到类路径,并使用getResourcesAsStream()

maven-surefire-plugin用于执行单元测试,使用additionalClasspathElement添加到类路径的资源仅在Maven的test阶段可用。 (即,除了单元测试之外,您不能在实际的应用程序代码中使用这些文件)。

更新: 我不确定该解决方案是否适用于您,但是可能的解决方法/解决方案是将文件位置作为JVM参数传递,然后使用FileInputStream读取文件。

示例: 传递jvm参数为-Dexternal.config.file.path=/Users/Documents/my-app-config.properties,然后在您的Java代码中读取文件。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ConfigFileReader {

    private static final Logger logger = LogManager.getLogger(ConfigFileReader.class);

    public static void readConfigFile() {

        String configFilePath = System.getProperty("external.config.file.path");
        try (InputStream inputStream = new FileInputStream(new File(configFilePath))) {
            // Do your stuff
        } catch (FileNotFoundException e) {
            logger.error("{} File not found",configFilePath);
        } catch (IOException e) {
            logger.error("IOException occurred while reading {}",configFilePath);
        }
    }

}
本文链接:https://www.f2er.com/3120997.html

大家都在问