【问题标题】:Spring boot can not find resource file after packagingspring boot打包后找不到资源文件
【发布时间】:2019-05-31 21:23:03
【问题描述】:

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

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

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;
}

【问题讨论】:

标签: spring resources


【解决方案1】:

您不能将 JAR 文件作为 URL 加载。您必须将其作为 InputStream 加载。

在你的情况下:

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

在此处阅读更多信息: Reading a resource file from within jar

【讨论】:

    【解决方案2】:

    我也遇到过类似的问题。

    class SomeClass{
      @Autowired
      ResourceLoader resourceLoader;
    
      void someFunction(){
        Resource resource=resourceLoader.getResource("classpath:preferences.json");
        Preferences defaultPreferences = objectMapper.readValue(resource.getInputStream(), Preferences.class);
     }
    }
    

    在本例中,我已将 JSON 数据映射到 Preferences 类。在您的情况下,您可以使用

    resource.getURL()
    

    供进一步使用。这适用于开发环境和部署,这意味着它也可以在您在 tomcat 中构建和部署 JAR/WAR 或使用 java -jar 时使用。

    【讨论】:

      猜你喜欢
      • 2020-01-03
      • 2017-05-01
      • 2019-08-11
      • 1970-01-01
      • 2023-03-31
      • 2017-05-21
      • 2019-09-24
      • 2015-10-02
      • 2012-05-16
      相关资源
      最近更新 更多