如何解决由于多个感叹号,SpringBoot 无法从 Runnable jar 加载属性文件
我有一个 Spring Boot 项目,在本地一切正常。现在,当我创建一个可运行的 jar 以通过 jenkins 运行它时,它无法加载属性文件。 以下是配置 PropertyPlaceholder 的代码:
@Bean
public static EncryptablePropertyPlaceholderConfigurer propertyPlaceholderConfigurerEncrypted() {
String env = System.getProperty("spring.profiles.active") != null ? System.getProperty("spring.profiles" +
".active") : "ci";
EncryptablePropertyPlaceholderConfigurer ppc =
new EncryptablePropertyPlaceholderConfigurer(getStandardPBEStringEncryptor());
ppc.setLocations(new ClassPathResource("application.properties"),new ClassPathResource("application-" + env + ".properties"));
return ppc;
}
为了调试,我在其中添加了以下代码:
try {
String s = new String(Files.readAllBytes(new ClassPathResource("application-" + env + ".properties").getFile().toPath()));
LOG.info(s);
} catch (IOException e) {
LOG.error("Unable to read file",e);
}
它给出了这个错误:
java.io.FileNotFoundException: class path resource [application-qa1.properties] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/var/hudson/workspace/pv/target/T-S-21.3.40.jar!/BOOT-INF/classes!/application-qa1.properties
17:23:44 at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:217)
我已确认文件位于此位置的 jar 中 BOOT-INF/classes/application-qa1.properties
如此有效的问题是由于从 jar /var/hudson/workspace/pv/target/T-S-21.3.40.jar!/BOOT-INF/classes!/application-qa1.properties
加载文件时路径中出现第二个感叹号引起的
理想情况下,感叹号应该只出现在 jar 名称之后。
有人可以就如何解决这个问题提出建议。
解决方法
您不能像这样从 JAR 中读取文件。你必须像这样使用 getResourceAsStream:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("application-" + env + ".properties");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。