【问题标题】:Spring @ConfigurationProperties inheritance/nestingSpring @ConfigurationProperties 继承/嵌套
【发布时间】:2017-08-21 00:10:07
【问题描述】:

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

这是我的 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;
}

【问题讨论】:

    标签: spring spring-boot properties configuration-files properties-file


    【解决方案1】:

    没有什么神奇的方法可以做到这一点。大小必须是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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-17
      • 2020-01-07
      • 2018-03-12
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多