Spring Boot Property Yml/Properties with List structure
Watch out. Depending on Spring version above code may not work!
This may!
private List<TeddyBear> list = new ArrayList<>;
public List<TeddyBear> getList() {
return list;
}
The trick is that the Spring factoring calls getList() and adds TeddyBears to the new ArrayList. On a null pointer there it nothing to add. Ditch the getter. Not used.
You only need further :
@Autowired
TeddyBearConfig teddyBearConfig;
Last remark: If you want it to test under SpringBootTest, you may need some more tips.
supply a test app as context. There must be a more elegant way, but I did it like this:
@SpringBootTest(classes = {TestApplication.class,..
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) throws Throwable {
SpringApplication.run(TestApplication.class, args);
}
}
use TestPropertySource if your app.properties is under the TestSources path:
@TestPropertySource(locations="classpath:application.properties")
This should work.
@Configuration
@PropertySource(name = "props", value = "classpath:teddy.properties", ignoreResourceNotFound = false)
@ConfigurationProperties(prefix = "teddy")
public class TeddyBearConfig {
private List<TeddyBear> list;
public List<TeddyBear> getList() {
return list;
}
public void setList(List<TeddyBear> list) {
this.list = list;
}
public static class TeddyBear {
private String name;
private String price;
public TeddyBear() {
}
public TeddyBear(String name, String price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
}
Update :
Above code works for the properties file you have given above.
If you wish to use yml file, you can do so. but there are a few points.
1. You yml structure isn't correct, it should be like this
teddy:
list:
-
name: Red
price: Five
-
name: Blue
price: One
-
name: Yellow
price: Two
-
name: Green
price: Three
2. After fixing your yml structure, (and also file name in your TeddyBearConfig), you will see that springboot doesn't complaint during startup, but list variable in TeddBearConfig will be null. This is a bug in the way springboot handles yml files through @PropertySource
.
3.If you move this yml content to application.yml
and remove @PropertySource
line in your config file, you would see that everything works perfectly fine.