【问题标题】:How do I express a list or array of objects in yaml via a Spring placeholder?如何通过 Spring 占位符在 yaml 中表达对象列表或数组?
【发布时间】:2019-04-07 01:53:25
【问题描述】:

我知道您可以使用如下占位符覆盖 yaml 配置值:

some-setting: ${SOME_SETTING:default value}

我知道你可以像这样表达对象列表:

customers:
  - name: acme
    category: manufacturing
    employees: 200 
  - name: virtucon
    category: evil
    employees: 1

那么我将如何通过 ${} 占位符表示法来表达这样的列表?

【问题讨论】:

    标签: spring spring-boot properties yaml placeholder


    【解决方案1】:

    您必须创建一个 ConfigurationProperties 才能读入属性对象。

    @Component
    @ConfigurationProperties("app")
    public class AppProperties {
    
        private List<Customer> customers = new ArrayList<>();
    
        public static class Customer {
            private String name;
            private String category;
            private int employees;
        }
    }
    

    通常你也会在你的 .yml 文件中为此创建一个前缀

    app:
       customers:
       - name: acme
         category: manufacturing
         employees: 200
       - name: virtucon
         category: evil
         employees: 1 
    

    您现在可以在应用程序的任何位置自动连接此类。

    【讨论】:

    • 不是完全相同的东西。我知道如何从 YAML 读取属性,这里的想法是在静态 YAML 中使用 Spring ${} 占位符符号,以便可以将值注入其他地方。
    • 我认为不可能使用值占位符来读取复杂的对象。您可以获得像这样的单个字段 @Value("${customers[0].name}") docs.spring.io/spring-boot/docs/current/reference/html/…
    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 2016-07-13
    • 2021-02-23
    • 1970-01-01
    相关资源
    最近更新 更多