当前位置: 首页 > 知识库问答 >
问题:

将YAML列表映射到Spring Boot中的对象列表

壤驷穆冉
2023-03-14

YAML文件:

config:
    gateways:
        -
            id: 'g0'
            nbrInputs: 128
            nbrOutputs: 128
        -
            id: 'g1'
            nbrInputs: 128
            nbrOutputs: 128

配置类:

@Configuration
@ConfigurationProperties(prefix="config")
public class GatewayConfig
{
    List<Gateway> gateways = new ArrayList<Gateway>();

    // Getter/Setter for gateways
    // ...

    public static class Gateway
    {
        private String id;

        @Value("${nbrInputs}")
        private int numInputs;

        @Value("${nbrOutputs}")
        private int numOutputs;

        // Getters and Setters
        // ...
    }
}

我希望@value注释允许我注入相应的属性值,但这似乎不起作用(注入'id'字段似乎工作得很好)。

共有1个答案

汪晨
2023-03-14

正如Stephave Nicoll提到的,@value注释与@configurationproperties无关。只需将内部POJO中的字段命名为与配置文件中相同的字段,这将起作用:

@Configuration
@ConfigurationProperties(prefix="config")
@EnableConfigurationProperties
public class GatewayConfig
{
    List<Gateway> gateways = new ArrayList<Gateway>();

    // Getter/Setter for gateways
    // ...

    public static class Gateway
    {
        private String id;
        private int nbrInputs;
        private int nbrOutputs;

        // Getters and Setters
        // ...
    }
}

对评论的反应:

使用普通的spring/spring Boot,我不认为您可以映射具有不同名称的字段并将其加载到网关列表中。可以选择使用普通@value注释,但您的网关计数需要硬编码:

@Component
public class Gateway0{
    @Value("${config.gateways[0].id}")
    private String id;

    @Value("${config.gateways[0].nbrInputs}")
    private int numInputs;

    @Value("${config.gateways[0].nbrOutputs}")
    private int numOutputs;

    // Getters and Setters
    // ...
}
 类似资料:
  • 我正在尝试在我的应用程序中注入列表。我的Spring Boot应用程序中Java对象列表的yml文件。 我已经看到了其他类似问题的一些答案,这些问题将Yaml中的列表映射到Spring Boot中的对象列表,但我有不同的输出错误。 我的YAML文件 我还创建了Bucket类 以及我的配置类,我在其中将列表注入YAML 当Spring Boot开始执行时,我出现以下错误: 我也尝试过简单的字符串列表

  • 问题内容: 在我的Spring Boot应用程序中,我具有以下内容的application.yaml配置文件。我想将其作为带有通道配置列表的Configuration对象注入: 我想用PaymentConfiguration对象列表填充@Configuration对象: 我使用@Autowired构造函数将其作为普通bean注入。xyz的值正确填充,但是当Spring尝试将yaml解析为对象列表时

  • 有什么线索吗?这里出了什么问题?

  • 我正在尝试将yml文件映射到Spring boot应用程序中具有字符串键和PromotionPolicy值的HashMap,并使用默认的Spring boot实现来解析这些值,但当我尝试从映射中读取值时,PromotionPolicy对象只包含所有实例的默认值[0,false,false]。 我的yml是: 我拥有的模型是: 组件java类如下: 尝试在此处显示值: 我的输出如下: 而我希望结果包

  • 给定: 我想把所有的车都标出来。将轮胎分为单独的轮胎板。我知道我可以做一个

  • 下面是我的DTO。 源DTO 目标DTO