Java 在Spring Boot中将YAML列表映射到对象列表
我有一个与中描述的问题类似的问题,只是我想将对象中至少一个字段的标识符与YAML中使用的对应键名不同 例如: YAML文件:Java 在Spring Boot中将YAML列表映射到对象列表,java,spring,spring-boot,configuration,yaml,Java,Spring,Spring Boot,Configuration,Yaml,我有一个与中描述的问题类似的问题,只是我想将对象中至少一个字段的标识符与YAML中使用的对应键名不同 例如: YAML文件: config: gateways: - id: 'g0' nbrInputs: 128 nbrOutputs: 128 - id: 'g1' nbrInputs: 128 nbrOutput
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
// ...
}
}
@配置
@配置属性(前缀=“配置”)
公共类网关配置
{
列表网关=新的ArrayList();
//网关的Getter/Setter
// ...
公共静态类网关
{
私有字符串id;
@值(“${NBR}”)
私有整数;
@值(“${NBR}”)
私人国际努穆特普茨;
//接球手和接球手
// ...
}
}
我希望@Value注释允许我注入相应的属性值,但这似乎不起作用(“id”字段的注入似乎很好)
有没有办法用@Value(或任何其他注释)来实现这一点
多谢各位
编辑:
请注意,我希望确定是否可以在不更改任何一个属性的名称的情况下,强制YAML属性与内部POJO中的字段进行对应。我之所以希望这样做,有几个原因-例如,我可能无法控制YAML文件的格式,我希望在POJO中使用比YAML文件作者使用的更具描述性的标识符名称。正如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
// ...
}
}
您根本不需要
@值。嵌套对象将自动考虑在内。删除@Value
并为num****添加getter/setter感谢您的快速响应,Nicoll先生。我已经有了numInputs和numOutputs的getter和setter。我无法弄清楚的是,如何使YAML文件中的'nbrimpts'的值被注入对象中的'numinput'(而'nbrimports'被注入'numOutputs')。当然,我可以将Gateway类中的字段更改为'nbrimpts'和'nbrimputs',但我想知道我是否可以在不这样做的情况下使其工作。谢谢。不,你不能那样做。@ConfigurationProperties
的主要目的是将环境绑定到对象模型,两者之间没有“转换”。话虽如此,没有人阻止你自己创建这样的对象并将其转换为“真实”类型。谢谢你的回复。这确实会起作用。但是请注意,我希望确定是否可以在不更改YAML属性和内部POJO中的字段名称的情况下强制YAML属性和字段之间的对应关系。我对原始问题进行了编辑,以澄清这一意图。嗨@luboskrnac,请调查这是一个类似的问题。
@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
// ...
}