【发布时间】:2018-05-01 13:11:30
【问题描述】:
情况
我有一个 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 值。
【问题讨论】:
-
文件可读吗?它是否具有正确的权限,以便您的应用程序可以实际读取文件。
-
是的。为了确保这不是错误,我给了每个使用过的读取权限,并以管理员身份运行了 jar。
-
你的
@SpringBootApplication注释类是什么样的。您不会尝试使用@PropertySource自己加载文件吗? -
不,我不是,我已将
@SpringBootApplication课程添加到主帖中。 -
不要添加
PropertySourcesPlaceholderConfigurerSpring Boot 会处理这个问题。如果它不起作用,您的应用程序中的某些内容会禁用常规行为。
标签: java spring-boot configuration application.properties