Spring @ConfigurationProperties 继承/嵌套

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

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

相关文章:

java - Spring、CORS 和 j_spring_security_logout

java - 更改 Spring Boot 中的 application.yaml 以返回尽可能长的日期而不是时间戳

spring-boot - 有什么理由不将小型 spring-boot 启动器与自动配置放在一起?

ios - 可以容纳不同类对象的属性 "currentViewController"

java - 如何在不删除其他变量的情况下更新java中的属性值

java - JPA CriteriaQuery 实现 Spring Data Pageable.getSort()

java - spring 错误 :org. springframework.web.context.ContextLoader - 上下文初始化失败

spring-boot - 使用 Spring REST Docs 记录空值

java - 如何使用带有 spring api 的 JPA 查询进行软删除?

java - HOCON替换默认值