Search code examples
javalistspring-bootyamlbind

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


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;


Solution

  • 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