Spring @ConfigurationProperties inheritance/nesting

Spring @ConfigurationProperties inheritance/nesting

如何加载配置以创建继承默认值并支持覆盖的 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"  
      }
    ]
  }
}

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

@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,如果需要,您应该 post 处理您的配置以应用默认值。

一样简单的东西
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
    }
}