How to bind yaml list to a java list in springboot?

11,605

Solution 1

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

Solution 2

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.

Share:
11,605

Related videos on Youtube

curious_cat
Author by

curious_cat

Updated on June 13, 2022

Comments

  • curious_cat
    curious_cat almost 2 years

    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;

Related