Search code examples
javaspringconfiguration

Properties in @Configuration nested classes not loaded from application.yaml without @ConfigurationProperties on nested class


Trying this code:

@Configuration
@ConfigurationProperties(prefix = "aa")
@Validated
@Setter
@Getter
public class AA {

    ...

    private BB bb;

    @Bean
    public BB bb() {
        return new BB();
    }

    @Setter
    @Getter
    public static class BB {

        private String someProperty;
    }
}

application.yaml

aa:
  bb: 
    someProperty: somevalue

When running the application 'somevalue' is not loaded to someProperty. However, it is loaded if I add @ConfigurationProperties(prefix = "aa.bb") to class BB. Why is this needed? Spring is supposed to automatically construct the prefix for class BB using the property private BB bb in AA class.


Solution

  • Initialise the bb variable with the default constructor new BB() and delete your method with @bean. Next, Spring will use the getters and setter to initialise the field of the object BB

    @Validated
    @Configuration
    @ConfigurationProperties(prefix = "aa")
    public class AA {
      private final BB bb = new BB();
      public BB getBb() { return bb; }
     
      public static class BB {
        @NotBlank
        private String someProperty;
        public String getSomeProperty() { return someProperty;}
        public void setSomeProperty(String someProperty) { this.someProperty = someProperty;}
      }
    
    }