小结
Spring Boot需要生成可执行Jar文件,并对其进行云布署(Kubernetes Container),这里对配置文件的处理与在本地运行有区别,需要考虑到能够正常读取到配置文件,这里进行了测试, 成功读取Resources下的Config目录的配置文件。
问题
Spring Boot生成可执行Jar文件,如果欠缺考虑,没有正确地处理配置文件的加载,基本上会碰到以下问题:
cannot be resolved to absolute file path because it does not reside in the file system
解决
以testapp.properties
这个配置文件为例,它在resources/config/testapp.properties
这个目录下,先前通过以下办法:
ApplicationConfigFile = ResourceUtils.getFile("classpath:config/testapp.properties").toPath();
在本地调试环境中是可以正常操作运行,但是,在Spring Boot生成可执行Jar文件里进行运行时,是没有办法正确加载的。
通过以下办法可以解决问题,在Spring Boot生成可执行Jar文件里可以正确加载相关配置文件。
InputStream inputStream = null;
ClassPathResource resource = new ClassPathResource("config/testapp.properties");
URL resourceUrl = null;
try {
resourceUrl = resource.getURL();
} catch (IOException e) {
}
if (resourceUrl != null) {
inputStream = resourceUrl.openStream();
} else {
inputStream = new ClassPathResource("config/testapp.properties").getInputStream();
}
经过以上操作后,可以对这个读取的inputStream
进行操作。
log4j2.xml
这个配置文件的存放目录是resources/config/log4j2.xml
,处理办法有些特别 可以通过如下办法:
InputStream inputStream = null;
inputStream = new ClassPathResource("config/log4j2.xml").getInputStream();
Configurator.initialize(null, "config/log4j2.xml");
其它问题解决
问题 Circular dependency between the following tasks
,这里是出现了模块引用了自己,在build.gradle
里注释掉以下testapp引用自己的行:
// ...
dependencies {
//implementation project(':testapp') // 'testapp' depends on 'testapp' !!!
// ...
}
调试时碰到 'Source code does not match the bytecode' when debugging on a device
,可以通过以下办法解决。
在IntelliJ IDEA中做以下操作:
- Click on “File”
- Click on “Invalidate Caches / Restart …”
- Choose: “Invalidate and Restart”
IntelliJ IDEA重启后可以正常调试。
使用以下办法可以将先前得到的InputStream
转换成Reader
,
Reader targetReader = new InputStreamReader(inputStream);
参考
CSDN: SpringBoot打开resources目录下的文件操作
Stackoverflow: Circular dependency between the following tasks
Stackoverflow: ‘Source code does not match the bytecode’ when debugging on a device
Stackoverflow: File inside jar is not visible for spring
cnblog: 导出报错cannot be resolved to absolute file path because it does not reside in the file system
Stackoverlfow: Caused by: java.io.FileNotFoundException: class path resource [application.properties] cannot be opened because it does not exist
Baeldung: Java – InputStream to Reader
Baeldung: Change the Default Location of the Log4j2 Configuration File in Spring Boot