春季@ConfigurationProperties继承/嵌套



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

这是我的应用程序.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
    }
}

最新更新