Unable to read yml properties as List in Spring Boot

Viewed 140

I am trying to read a list of servers in my Spring Boot app using @ConfigurationProperties. However I am getting below error. Is there something I am doing wrong in terms of syntax in yaml?

ApplicationServer

@Component
@ConfigurationProperties(prefix = "application")
public class ApplicationServer {

    List<Server> servers;

    public List<Server> getServers() {
        return servers;
    }

    public void setServers(List<Server> servers) {
        System.out.println("setter called "+servers);
        this.servers = servers;
    }
}

Server

@Component
public class Server {

    String ip;
    String path;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

DemoApplication

@SpringBootApplication
@EnableConfigurationProperties(ApplicationServer.class)
public class DemoApplication implements CommandLineRunner {

@Autowired
ApplicationServer applicationServer;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        System.out.println(applicationServer.servers);
    }
}

application.yml

application:
    servers:
      -   ip:123
          path:xyz
      -   ip:456
          path:abc
      -   ip:789
          path:pqrs

ERROR

 Property: application.servers[0]
    Value: ip:123 path:xyz
    Origin: class path resource [application.yml] - 3:11
    Reason: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [com.example.demo.Server]
1 Answers

application.yaml modified as:

application:
  servers:
    - {ip: 123,path: xyz}
    - {ip: 456,path: abc}
    - {ip: 789,path: pqrs}

or

application:
  servers:
    - ip: 123
      path: xyz
    - ip: 456
      path: abc
    - ip: 789
      path: pqrs

Space required after colon

Related