0

application.properties:

my.list=1,2,3,4

I want to inject this as a List into a @Value field:

@Value("${my.list}")
List<Integer> list;

On the net I found that the following bean has to be registered for this to work:

@Bean
public ConversionService conversionService() {
    return new DefaultConversionService();
}

Result:

org.springframework.beans.TypeMismatchException: Failed to convert value of type [java.lang.String] to required type [java.util.List];
Caused by: java.lang.NumberFormatException: For input string: "1,2,3,4"

Somehow spring is not trying to parse this as a list. Why?

I know it is possible using spEL with @Value("#{'${my.list}'.split(',')}"), but I'm explicit looking in a solution without spel conversation.

membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

-1

Spring is looking for a setter like setList(String), since there isn't, tries to convert the value. You can solve that by creating a setList(String[] arg) method witch parses each element of arg and then sets the list

setList(String[] arg){
    if (arg == null){
        this.list = new ArrayList<>();
    } else {
        this.list = new ArrayList<>(arg.length);
        for (String s : arg){
            this.list.add(Integer.parse(s));
        }
    }
}

I think Spring can access such setter even if it's private, but try with public first, and then reduce visibility if it works

dtortola
  • 768
  • 4
  • 6