Spring boot打包后找不到资源文件

2024-03-21

我使用 Spring boot maven 插件将应用程序打包为 jar 文件。

可以找到资源文件直接在Intellij IDEA中运行, 但之后找不到资源文件,显示错误为:

java.io.FileNotFoundException:类路径资源 [jmxremote.password] 无法解析为绝对文件路径,因为它不驻留在文件系统中:jar:file:/home/XXX/target/YYY.jar!/BOOT-INF /classes!/jmxremote.password

但是,jar 文件中确实存在文件“jmxremote.password”。

    private Properties initialJMXServerProperties() throws RuntimeException {
    URL passwordURL = JMXConfig.class.getClassLoader().getResource(passwordFileName);
    URL accessURL   = JMXConfig.class.getClassLoader().getResource(accessFileName);

    String passFile     = Optional.ofNullable(passwordURL).map(URL::getPath).orElseThrow(() -> new RuntimeException("JMX password file not exist"));
    String accessFile   = Optional.ofNullable(accessURL).map(URL::getPath).orElseThrow(() -> new RuntimeException("JMX access file not exist"));

    Properties properties = new Properties();
    properties.setProperty(PASSWORD_FILE_PROP, passFile);
    properties.setProperty(ACCESS_FILE_PROP, accessFile);
    return properties;
}

您无法从 JAR 作为 URL 加载文件。您必须将其作为输入流加载。

在你的情况下:

InputStream passwordInputStream = 
                 JMXConfig.class.getClassLoader().getResourceAsStream(passwordFileName);

阅读更多相关内容:从jar中读取资源文件 https://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring boot打包后找不到资源文件 的相关文章

随机推荐