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); } }
Looks like you are missing @ConfigurationPropertiesScan
https://www.baeldung.com/configuration-properties-in-spring-boot
UPD: an implementation example was found here: https://www.baeldung.com/spring-boot-yaml-list
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.