Spring boot在打包后找不到资源文件
我使用SpringBootMaven插件将应用程序打包为jar文件 它可以在Itellij IDE中找到直接运行的资源文件, 但之后找不到资源文件,显示错误为: java.io.FileNotFoundException:类路径资源[jmxremote.password]无法解析为绝对文件路径,因为它不位于文件系统:jar:file:/home/XXX/target/YYY.jar/BOOT-INF/classes/jmxremote.password 但是,jar文件中确实存在文件“jmxremote.password”Spring boot在打包后找不到资源文件,spring,resources,Spring,Resources,我使用SpringBootMaven插件将应用程序打包为jar文件 它可以在Itellij IDE中找到直接运行的资源文件, 但之后找不到资源文件,显示错误为: java.io.FileNotFoundException:类路径资源[jmxremote.password]无法解析为绝对文件路径,因为它不位于文件系统:jar:file:/home/XXX/target/YYY.jar/BOOT-INF/classes/jmxremote.password 但是,jar文件中确实存在文件“jmxre
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;
}
不能将文件作为URL从JAR加载。您必须将其作为InputStream加载 就你而言:
InputStream passwordInputStream =
JMXConfig.class.getClassLoader().getResourceAsStream(passwordFileName);
请在此阅读更多信息:
我也遇到过类似的问题
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时,它也可以工作。可能的重复