Search code examples
javaarraysspring-bootyamlsnakeyaml

Read Integer List from yaml file


The current implementation is :-

public static final List<Integer> validCodes = Collections.unmodifiableList(Arrays.asList(110, 210, 310,510,610));

However, I am not happy with this approach as this of hard coded. I want to make it configurable instead of hard-coded. I suppose reading this values from the yaml file would solve my problem.

But how do I define a list of Integer in the yaml file and real it using @value. I can find a lot of example about reading list of strings but not integers.


Solution

  • Within the application.yml file, define the config variable as follows.

    my_integers: 1231,12323,12321

    then use the @Value annotation to make to an Integer list as follows.

    @Value("#{'${my_integers}'.split(',')}")
    private List<Integer> myIntegers;
    

    Spring does the rest. You only need to use myIntegers with your need. Happy coding....

    PS: I have used spring boot 2.0.*