application.yml custom properties(array) with spring boot

Intellij application.yml custom array properties and use with spring boot

Spring Boot, How to use application.yml customize properties for array data 

 

 

Appplication.yml’s content as below:  

 

my: 
    servers: 
        - name: Linux1 
           ip: 192.168.12.3 
 
       name: Linux2 
            ip: 192.168.12.4 
 
        name: Linux3 
            ip: 192.168.12.5 

 

My.java’s content as below: 

 

@Component 

@ConfigurationProperties(prefix = "my") 

public class My { 

    private List<Server> servers; 

    public List<Server> getServers() { 

        return servers; 

    } 

    public void setServers(List<Server> servers) { 

        this.servers = servers; 

    } 

    public My() { 

    } 

 

    public static class Server 

    { 

        private String name; 

        private String ip; 

        public String getName() { 

            return name; 

        } 

        public void setName(String name) { 

            this.name = name; 

        } 

        public String getIp() { 

            return ip; 

        } 

        public void setIp(String ip) { 

            this.ip = ip; 

        } 

        @Override 

        public String toString() { 

            return "Server{" + 

                    "name='" + name + '\'' + 

                    ", ip='" + ip + '\'' + 

                    '}'; 

        } 

    } 

} 

 

UserController.java’s content as below 

 

public class UserController { 
 

  @Autowired 
  private My my; 

 

 

    @PostMapping("/user") 

    public String selectLinuxClient(String hostname) 

    { 

        this.hostname = hostname; 

        List<My.Server> serverList = my.getServers(); 

        int selectIndex = -1; 

        for (int index=0; index < serverList.size();index++) 

        { 

            if (serverList.get(index).getName().equals(hostname)) 

            { 

                selectIndex = index; 

                break; 

            } 

        } 

        if (selectIndex == -1) 

        { 

            return "user"; 

        } 

 

       String ip =""; 

        ip = serverList.get(selectIndex).getIp() + ":8080";