Guisong He
Guisong He

Reputation: 1976

spring boot: unable to bind yaml list objects

I need to bind a list of POJO by yaml properties file but I was no luck to get it work. My application.yml has the following lines:

printer:
  printers:
    - deviceNo: abc
      key: 123

And PrinterProperties like this:

@Component
@ConfigurationProperties(prefix = "printer")
class PrinterProperties {
    var printers: List<Printer> = listOf()
}

But the field printers was not poputated with the application.ymlvalue.

There was a samilar problem

I pushed a demo to a github repository to demostrate this problem.

Upvotes: 0

Views: 2355

Answers (3)

Liping Huang
Liping Huang

Reputation: 4476

printer:
  printers:
    - 
      deviceNo: abc
      key: 123

Your yaml file should like this.

Upvotes: 0

Guisong He
Guisong He

Reputation: 1976

From Andy Wilkinson's advice: the POJO should have a default constructor. So I changed the POJO with:

class Printer {
    var deviceNo: String? = null
    var key: String? = null
}

and it works now.

Upvotes: 1

As described in the Spring Boot docs at Externalized Configuration page, you can bind properties like that in your example as long they accomplish one of this conditions:

1) The class property has a setter

2) It's initialized with a mutable value.

listOf() will give you an unmutable value therefore it won't work.

Hope it helped! :)

Upvotes: 1

Related Questions