【问题标题】:Mapping YAML List to List of Objects in Spring Boot将 YAML 列表映射到 Spring Boot 中的对象列表
【发布时间】:2016-07-13 22:18:32
【问题描述】:

我有一个类似于Mapping list in Yaml to list of objects in Spring Boot 中描述的问题,除了我想将我的对象中至少一个字段的标识符与 YAML 中使用的相应键名不同。

例如:

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' 字段似乎工作得很好)。

有没有办法使用@Value(或任何其他注释)来做到这一点?

谢谢。


编辑: 请注意,我希望确定是否可以强制 YAML 属性和内部 POJO 中的字段之间建立对应关系而不更改两者的名称。我可能想这样做有几个原因 - 例如。我可能无法控制 YAML 文件的格式,我想在我的 POJO 中使用比 YAML 文件作者使用的更具描述性的标识符名称。

【问题讨论】:

  • 您根本不需要@Value。自动考虑嵌套对象。删除 @Value 并为 num**** 添加 getter/setter
  • 感谢您的快速回复,Nicoll 先生。我已经有了 numInputs 和 numOutputs 的 getter 和 setter。我无法弄清楚的是如何使 YAML 文件中的“nbrInputs”的值注入对象中的“numInputs”(以及“nbrOutputs”注入“numOutputs”)。当然,我可以将 Gateway 类中的字段更改为“nbrInputs”和“nbrOutputs”,但我想知道是否可以不这样做就使其工作。谢谢。
  • 不,你不能那样做。 @ConfigurationProperties 的主要目的是将环境绑定到对象模型,没有“中间转换”。话虽如此,没有人会阻止您自己创建此类对象并将其转换为“真实”类型。

标签: java spring spring-boot configuration yaml


【解决方案1】:

正如 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
    // ...
}

【讨论】:

  • 感谢您的回复。这确实会奏效。不过请注意,我希望确定是否可以强制在 YAML 属性和内部 POJO 中的字段之间建立对应关系而不更改其中任何一个的名称。我已经编辑了原始问题以澄清这一意图。
  • 嗨@luboskrnac,请查看stackoverflow.com/questions/57409781/…这是一个类似的问题。
猜你喜欢
  • 2015-12-12
  • 2019-07-25
  • 1970-01-01
  • 2018-11-23
  • 2017-02-17
  • 2019-07-08
  • 2018-12-11
  • 2019-12-06
  • 1970-01-01
相关资源
最近更新 更多