Home > Back-end >  unable to bind list of object properties from application.yml in spring
unable to bind list of object properties from application.yml in spring

Time:07-02

I want to bind a list of object properties to a field in spring bean, but spring does not bind it. What am I missing? My env is SpringBoot v2.7.1 Java 8.

application.yml

application:
  mappings:
    -   oldname: 'old name 1'
        newname: 'new name 1'
    -   oldname: 'old name 2'
        newname: 'new name 2'

MappingProperties.java

@ConfigurationProperties(prefix = "application")
public class MappingProperties {
    private List<Mapping> mappings;

    public List<Mapping> getServers() {
        return mappings;
    }

    public void setServers(List<Mapping> mappings) {
        this.mappings = mappings;
    }

    public class Mapping {
        private String oldname;
        private String newname;

        public String getOldname() {
            return oldname;
        }

        public void setOldname(String oldname) {
            this.oldname = oldname;
        }

        public String getNewname() {
            return newname;
        }

        public void setNewname(String newname) {
            this.newname = newname;
        }
    }
}

DemoApplication.java

@EnableConfigurationProperties(MappingProperties.class)
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    @Autowired
    private MappingProperties mappingProperties;

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

    @Override
    public void run(String... args) throws Exception {
        System.out.println(mappingProperties);
    }
}

CodePudding user response:

Looks like you are missing @ConfigurationPropertiesScan https://www.baeldung.com/configuration-properties-in-spring-boot

  • Related