首页 > 解决方案 > 如何在 Spring 框架之外加载 Spring YAML 配置?

问题描述

我有一个 Spring Boot 应用程序,它在 application.yml 配置文件中定义了一些端点。YAML 包含多个文档,每个配置文件一个。

我想在启动应用程序之前运行 Gradle 任务。Gradle 任务将配置文件作为参数传递。它应该使用该配置文件的配置中定义的端点。

如何在不加载整个 Spring 框架的情况下从配置中加载值?

例子

# src/main/resources/application.yml
endpoints: 
  foo: localhost:12345/foo
  bar: localhost:12345/bar

---
spring.profiles: staging
endpoints:
  foo: dev.foo.com/api
  bar: dev.bar.com/api

--- 
spring.profiles: production
endpoints:
  foo: foo.com/api
  bar: bar.com/api
public class Task {
    public static void main(String[] args) {
        String profile = arg[0];

        // TODO load endpoints from src/main/resources/application.yml
        Map<String, Object> endpoints = ...
        System.out.println(endpoints.get("foo");
    }
}

标签: javaspringyaml

解决方案


推荐阅读