情况
我有一个 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.propertiesjar 之外的文件。
当application.properties放置相同的文件时,src/main/resources它可以正常工作,因此配置文件似乎是正确的。
任何想法为什么它不会加载外部配置文件?
编辑 1
我也试过用--spring.config.location=file:application.propertiesand运行它,--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值。