I have a list in my yml file which i need to bind in my java springboot application, how do i go about it ?
fruits:
- Apple
- Bannana
Ideally i want something like
@Value("${filters.siteID}")
List siteIDs;
The documentation has an example in "24.6.1 Loading YAML"
Define your list like
my:
fruits:
- Apple
- Bannana
And create a config properties class to represent it:
@Component
@ConfigurationProperties(prefix="my")
public class FruitConfig {
private final List<String> fruits = new ArrayList<String>();
public List<String> getFruits() {
return this.fruits;
}
}
Then use this class in your code in places that need the config
@Autowired
FruitConfig fruitConfig;
... {
System.out.println(fruitConfig.getFruits());
}
direct binding to @Value
doesn't seem to work because of the way @Value
works
There is also another opportunity if you want to avoid to create a property class and keep using @Value
and if your list is not very long.
Define your list like
my:
fruits: Apple,Banana
And use it, e.g.
with Kotlin
@Value("#{'\${my.fruits:}'.split(',')}")
private lateinit var fruits: List<String>
or Java
@Value("#{'${my.fruits:}'.split(',')}")
private final List<String> fruits = new ArrayList<>();
Note: the colon after fruits
is optional to avoid startup errors if you use multiple profiles and this property does not exist in all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With