java - Spring Boot jar 不读取/解析 application.properties 根文件夹
问题描述
情况
我有一个 Spring Boot 应用程序的胖 .jar。我已经用一个application.properties
文件将我的配置外部化了。该文件与 .jar 位于同一文件夹中,我从同一文件夹中的命令行启动 .jar(使用命令“java -jar $jarFileName”)。
然后抛出异常:
nested exception is org.springframework.beans.TypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is
java.lang.NumberFormatException: For input string: "${elasticsearch.port}"
如您所见,它没有从属性文件中读取值,而是将字符串设置为 @Value 注释中的文本,如下所示:
@Value("${elasticsearch.port}")
private int elkPort;
发生这种情况的类用 注释@Component
。根据Spring docs: externalized configuration,spring 应该读取application.properties
jar 之外的文件。
当application.properties
放置相同的文件时,src/main/resources
它可以正常工作,因此配置文件似乎是正确的。
任何想法为什么它不会加载外部配置文件?
编辑 1
我也试过用--spring.config.location=file:application.properties
and运行它,--spring.config.location=file:/full/path/to/application.properties
但结果与上面相同。
编辑 2:类路径尝试
也尝试classpath
了代替file
,与上面的命令相同,但file
替换为classpath
. 最后尝试没有任何一个,所以只是--spring.config.location=/path/to/file
; 再次使用相对路径和完整路径application.properties
。所有尝试都给出了相同的结果/异常。
编辑 3 我带注释的应用程序:
@SpringBootApplication
public class ApplicationName {
public static void main(String[] args) {
SpringApplication.run(ApplicationName.class, args);
}
}
编辑 4
尝试添加PropertySourcesPlaceholderConfigurer
如下:
@Configuration
public class PropertyConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
然后为每个@Value
我添加一个默认值;它仍然只解析为默认值而不是application.properties
值。
解决方案
好吧,经过一番挣扎,我找到了解决方案。我很接近PropertySourcesPlaceholderConfigurer
但还没有到那里;这是现在的完整课程:
@Configuration
public class PropertyConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
final PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setIgnoreResourceNotFound(true);
final List<Resource> resources = new ArrayList<>();
resources.add(new FileSystemResource("relative/path/to/application.properties"));
ppc.setLocations(resources.toArray(new Resource[]{}));
return ppc;
}
}
编辑
为了演示该问题,我创建了一个存储库来显示该问题,请参见此处:https ://github.com/Locitao/test-external-properties
推荐阅读
- excel - 按年份分组的数据透视表
- c++ - 释放内存时如何防止此段错误?
- mysql - 比较 mySQL 中的值与正则表达式
- android - 如何使用隐式意图 kotlin 打开文件资源管理器并获取选定的文件路径
- xamarin - Xamarin form 4.3 Label using sans-serif front
- multithreading - Haskell 计算密集型线程阻塞所有其他线程
- olingo - Olingo OData 对 JSON 的响应
- sapui5 - SAPUI5 Fragment close 清除上一屏的数据
- asp.net-mvc - 是否可以使 GlobalConfiguration.Configure 异步?
- excel - 根据另一个工作表中的单元格值隐藏一个工作表中的行