gpt4 book ai didi

Spring @ConfigurationProperties 继承/嵌套

转载 作者:行者123 更新时间:2023-12-04 17:52:56 36 4
gpt4 key购买 nike

如何加载配置以创建继承默认值并支持覆盖的 Shape 列表?

这是我的 application.yml 文件的样子...

store:
default:
color: red
size: 10

shapes:
- id: square
size: 20

- id: circle
size: 30
color: black

- id: rectangle

这就是我想要的...

{
"catalog": {
"shapes": [
{
"color": "red", // default
"size": 20, // override
"id": "square"
},
{
"color": "black", // override
"size": 30, // override
"id": "circle"
},
{
"color": "red", // default
"size": 10, // default
"id": "rectangle"
}
]
}
}

到目前为止,我已尝试遵循但它在继承中缺少默认值。换句话说,默认值永远不会成为Shape的对象。

@lombok.Data
@Component
@ConfigurationProperties(prefix = "store")
public class Catalog {
private List<Shape> shapes;
}

@lombok.Data
public class Shape extends DefaultConfig {
private String id;
}

@lombok.Data
@ConfigurationProperties(prefix = "store.default")
@Component
public class DefaultConfig {
private String color;
private int size;
}

最佳答案

没有神奇的方法可以做到这一点。大小必须是 Integer 并且您应该对配置进行后处理以在需要时应用默认值。

简单到

public class Catalog {

private final DefaultConfig defaultConfig;

public Catalog(DefaultConfig defaultConfig) { ... }

@PostConstruct
public void initialize() {
// iterate over all the shapes and if the color or size is null
// apply the default value from defalutConfig
}
}

关于Spring @ConfigurationProperties 继承/嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43060745/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com