ConfigurationProperties for final fields doesn't work

Viewed 1555

I need to set data from application.yml file to my config class but when I trying to do it I get an error:

TestConfig is annotated with @ConstructorBinding but it is defined as a regular bean which caused dependency injection to fail.

My application.yml file looks like the following:

test:
  app:
    id: app_id

My TestConfig class looks like this:

@Configuration
@ConfigurationProperties(prefix = "test.app")
@ConstructorBinding
public class TestConfig {
    private final String id;

    public TestConfig(String id) {
        this.id = id;
    }
}

I'm trying to do like this but it doesn't work for me.
Where I was wrong?

1 Answers

According to :

https://www.baeldung.com/configuration-properties-in-spring-boot#immutable-configurationproperties-binding

You will need to remove the @Configuration from your TestConfig.class.

Furthermore, it's important to emphasize that to use the constructor binding, we need to explicitly enable our configuration class either with @EnableConfigurationProperties or with @ConfigurationPropertiesScan.

--------- Edited -----

@ConfigurationProperties(prefix = "test.app")
@ConstructorBinding
public class TestConfig {

    private final int id;

    public TestConfig (int id)
        this.id = id
    }

    public String getId() {
        return id;
    }

 
}



@SpringBootApplication
@ConfigurationPropertiesScan
public class YourApp{

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