Search code examples
springspring-bootpropertiesconfiguration-filesproperties-file

Spring @ConfigurationProperties inheritance/nesting


How do I load configuration to create a list of Shapes which inherits defaults and also support overriding?

Here is how my application.yml files looks like...

store:
  default:
    color: red
    size: 10

  shapes:
    - id: square
      size: 20

    - id: circle
      size: 30
      color: black

    - id: rectangle

And here is what I want...

{
  "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"  
      }
    ]
  }
}

So far I have tried following but its missing defaults in the inheritance. In other words, the defaults never makes into Shapes object.

@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;
}

Solution

  • There's no magic way to do that. The size must be an Integer and you should post-process your configuration to apply the defaults if need to be.

    Something as easy as

    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
        }
    }