【问题标题】:Read properties file in Spring Boot在 Spring Boot 中读取属性文件
【发布时间】:2016-04-29 15:30:43
【问题描述】:

如何在 Spring Boot 中从单独的文件中读取属性?

我正在尝试他在这里做什么..http://www.mkyong.com/spring/spring-propertysources-example/

但它不读取文件?

假设您在资源文件夹中有一个 file.properties。

你应该输入:

  spring.configuration.location: classpath:file.properties

在 application.properties 中指向文件。

然后在你的 MyConfig 类中

@Service
public class MyConfig{

    @Value("${prop.one}")
    private String propOne;

这不应该吗?我做错了什么

在某处有这样做的简单示例吗?

谢谢!

【问题讨论】:

    标签: properties spring-boot


    【解决方案1】:

    最简单的方法是创建一个application.properties,它将驻留在您的 jar 的根目录中

    src
      main
        resources
          application.properties
    

    Spring boot 会自动加载这个文件作为属性文件。这是 spring boot 的一个特殊功能,可以自动查找 application.properties。使用常规 Spring,您需要指定属性文件的位置。他们正在演示如何使用常规 spring 添加新的属性文件。

    对于与标准 application.properties 不同的属性文件,您可以将 @PropertySource 注释添加到您的配置类中。此注解会将属性加载到 spring 环境中。

    【讨论】:

    • 是的,我已经看到这是可行的,但是如何拥有一个单独的属性文件?是不是因为是 Spring Boot 才不行?
    • 嗯,好的。只是想先给出简单的方法。我添加了您需要用于第二个属性文件的注释。
    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 2021-11-22
    • 2019-01-11
    • 2018-10-16
    • 2020-02-14
    • 2018-10-27
    • 2020-07-01
    • 2021-11-27
    相关资源
    最近更新 更多