gpt4 book ai didi

java - Spring boot jar 不读取/解析 application.properties 根文件夹

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:23:06 24 4
gpt4 key购买 nike

情况

我有一个 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 应该读取 jar 之外的 application.properties 文件。

当将相同的 application.properties 文件放在 src/main/resources 中时,它工作正常,因此配置文件看起来是正确的。

知道为什么它不加载外部配置文件吗?

编辑 1我还尝试使用 --spring.config.location=file:application.properties--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 很接近,但还不够;这是完整的类(class):

@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

关于java - Spring boot jar 不读取/解析 application.properties 根文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50117111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com