javaspring-bootconfigurationproperties

@ConstructorBinding seems not to work in Spring Boot 2.5.4


I'm using Spring Boot 2.5.4 and am trying to initialize an immutable class from properties:

@Configuration
@ConfigurationProperties("test")
public class Config {
    public final String foo;
    
    @ConstructorBinding
    public Config(String foo) {
        this.foo = foo;
    }
}

application.yml:

test:
  foo: bar

Main class:

@SpringBootApplication
@ConfigurationPropertiesScan
public class Application implements CommandLineRunner {
    @Autowired Config config;
    public Application(Config config) {
        this.config = config;
    }

    public static void main(String[] args) { SpringApplication.run(Application.class, args); }

    @Override
    public void run(String... args) {
        System.out.println(config.foo);
    }
}

I would expect this to start and print "bar". However, it fails to start with

Parameter 0 of constructor in Config required a bean of type 'java.lang.String' that could not be found.

When I remove the @ConstructorBinding and add a setter and nullary constructor, it does work.


Solution

  • Add @ConstructorBinding in class level. And remove @Configuration annotation. Like this,

    @ConstructorBinding
    @ConfigurationProperties("test")
    public class Config {
        public final String foo;
        
        public Config(String foo) {
            this.foo = foo;
        }
    }