'Custom converter for an inner property with @ConfigurationProperties

One of the property in my Spring Boot property source needs to have a dynamic type. In the sample below, customConfig.props will have different set of keys, corresponding to the customConfig.bean value.

config:
  baseName: 'base name'
  configArray:
    - url: 'dummy url'
      customConfig:
        bean: com.example.demo.model.MyConfig
        props:
          name: 'my name'
    - url: 'second url'
      customConfig:
        bean: com.example.demo.model.MyConfigTwo
        props:
          secondName: 'my second name'

For this I have created a component with @ConfigurationProperties and an interface as shown below.

@ConfigurationProperties("config")
@Component
@Getter
@Setter
public class Config {
    private String baseName;
    private List<ConfigArray> configArray;

    @Getter
    @Setter
    public static class ConfigArray {
        private String url;
        private CustomConfig customConfig;
    }

    @PostConstruct
    public void print() {
        CustomConfig customConfig = this.configArray.get(0).getCustomConfig();
        System.out.println(customConfig.getBean());
        System.out.println(customConfig.getProps());
    }

}

@Getter
@Setter
public class CustomConfig {
    private String bean;
    private CustomProps props;
}

Here are the CustomProps interface and two implementations.

public interface CustomProps {}

@Getter
@Setter
public class MyConfig implements CustomProps {
    private String name;
}

@Getter
@Setter
public class MyConfigTwo {
    private String secondName;
}

Currently the PostConstruct function prints com.example.demo.model.MyConfig and null. I need Spring Boot to identify the actual implementation and construct the customProps accordingly. Is there a way to implement this?

This is what I did, after some research. But not working for me.

@Component
@ConfigurationPropertiesBinding
public class ConfigConverter implements Converter<Object, CustomConfig> {
    @Override
    public CustomConfig convert(Object from) {
        // parse "from" and create "CustomConfig"
        return new CustomConfig(); // create a sample to avoid compilation issues
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source