我遇到的问题类似于 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 注释允许我注入(inject)相应的属性值,但这似乎不起作用(“id”字段的注入(inject)似乎工作得很好)。
有没有办法用@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
// ...
}
}
对评论的 react :
使用普通的 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
// ...
}
关于java - 将 YAML 列表映射到 Spring Boot 中的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36232138/