Search code examples
javaspringdependency-injectionimmutability

Use constructor injection for spring ConfigurationProperties subclasses


I was looking at this https://www.baeldung.com/configuration-properties-in-spring-boot and was wondering if it was possible to use constructor injection for these in order to enforce some immutability properties.

For example would it be possible to do this:

@Component
@ConfigurationProperties("my-config")
public class MyConfig {

    private final List<String> values;

    public MyConfig(@Value("${values}") List<String> values) {
        this.values = ImmutableList.copyOf(values);
    }
}

And then in my yml config have

my-config.values:
  - foo
  - bar

But I get this error:

java.lang.IllegalArgumentException: Could not resolve placeholder 'values' in string value "${values}"

Solution

  • is possible with spring boot since version 2.2.0 documentation is here: Constructor binding adding the new annotation @ConstructorBinding.