【问题标题】:spring boot specific profile yaml not loadingspring boot 特定配置文件 yaml 未加载
【发布时间】:2016-05-02 09:28:31
【问题描述】:

我有一个yaml文件如下:-

spring:
  profiles: test
msg: test
---
spring:
  profiles : dev
msg: hello
---
spring:
  profiles : prod
msg: production

位于/src/main/java/resourcesapplication.yaml

我的代码从这个文件中读取值如下

@Configuration
@EnableConfigurationProperties
public class TestConfig {

    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

我创建了一个此类的 bean,如下所示:-

@Bean
public TestConfig testConfig() {
    return new TestConfig();
}

但尝试查看配置文件特定信息不适用于以下代码:-

public class Main implements CommandLineRunner{

    @Autowired
    private TestConfig testConfig;

    public static void main(String[] args) {

        SpringApplication.run(Main.class, args);

    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("it works!!!");
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   " + testConfig.getMsg());
    }
}

非常感谢这里的任何帮助。

谢谢, 阿马尔

【问题讨论】:

  • 如果您使用的是 Maven\Gradle,它应该在 src\main\resources\config 文件夹中,文件扩展名也应该是 .yml
  • 我添加了你提到的文件,更改了扩展名,使用 ./gradlew -Dspring.profiles.active=dev clean bootrun 运行它。但它打印 null

标签: java spring spring-boot yaml


【解决方案1】:

我解决了我的问题, 我的构建脚本中有一个自定义引导运行,它将我的 spring.profiles.active 系统属性覆盖为某个值。 我在这里和那里做了一些调整,现在它工作正常。 感谢大家的时间!!!!

【讨论】:

    【解决方案2】:

    您的 yaml 文件应以三个破折号 --- 开头并命名为“.yml”。 确保将其放置在 /src/main/resources/ 中,您当前的位置会将其放置在输出中的 resources 目录下,这不是您想要的。

    【讨论】:

    • 我也试过这个。但是 null 会在控制台中打印出来
    • 如果您在未指定配置文件的情况下启动,则不会出现任何值,因为您只为配置文件“test”、“prod”、“dev”指定了一个值。您可以指定默认值或设置一个默认配置文件来解决这个问题。
    • 我计划为不同的环境使用不同的属性,即开发、生产和测试环境的不同值。当我的应用程序启动时,这些值将被自动读取。
    猜你喜欢
    • 2015-11-19
    • 2020-05-07
    • 2019-02-22
    • 1970-01-01
    • 2018-03-05
    • 2016-10-24
    • 2016-04-06
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多