繁体   English   中英

Spring启动jar没有读取/解析application.properties根文件夹

[英]Spring boot jar not reading/parsing application.properties root folder

情况

我有一个胖的.jar的Spring启动应用程序。 我使用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:外化配置 ,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值。

如上所述,您应该指定外部配置位置

    $ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

尝试不使用文件关键字--spring.config.location = / full / path / application.properties

我刚从Eclipse Spring Boot项目中取出了我的application.properties,但它失败了。 然后我将文件放在项目根目录下的cfg文件夹中,并添加了程序参数:

--spring.config.location=cfg/application.properties

它再次起作用。 Mayby如果你尝试一个相对路径(没有前导/)到文件(没有“file:”)它将工作。

好吧经过一番挣扎,我找到了解决方案。 我与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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM