Spring boot can not find resource file after packaging

主宰稳场 提交于 2020-01-06 06:37:30

问题


I use Spring boot maven plugin to package application as jar file.

It can find the resource file direct run in Itellij IDE, But it can not find resource file after, it display error as :

java.io.FileNotFoundException: class path resource [jmxremote.password] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/XXX/target/YYY.jar!/BOOT-INF/classes!/jmxremote.password

However, the file "jmxremote.password" indeed exist in the jar file.

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

回答1:


You cannot load the file from a JAR as URL. You have to load it as an InputStream.

In your case:

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

Read more about here: Reading a resource file from within jar




回答2:


I have also faced similar issue.

class SomeClass{
  @Autowired
  ResourceLoader resourceLoader;

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

In this case, I have mapped JSON data to the Preferences class. In your case, you may use

resource.getURL()

for further use. This works for both the development environment and deployment, means it also works when you build and deploy JAR/WAR in tomcat or use java -jar.



来源:https://stackoverflow.com/questions/54053603/spring-boot-can-not-find-resource-file-after-packaging

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!