Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

like image 493
curious_cat Avatar asked Dec 06 '22 17:12

curious_cat


2 Answers

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

like image 186
zapl Avatar answered Dec 09 '22 13:12

zapl


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.

like image 30
Tommy K. Avatar answered Dec 09 '22 13:12

Tommy K.