无法从application.yml加载属性

时间:2019-02-03 17:31:03

标签: java spring spring-boot

我想将服务器属性从application.yml加载到Configuration类。 我已经看到很多人已经问过同样的问题,但是没有一个对我有用:( 请帮我弄清楚我想念的东西

@Configuration
  @ConfigurationProperties("demo")
  public class Democonfig {
    private List<Archive> archive = new ArrayList<>();
    public Democonfig(List<Archive> archive) {
        this.archive = archive;
    }
    // Getter and setter
   public static class Archive {
        private String host;
        private String database;
        private String port;

        public Archive(String host, String database, String port) {
            this.host = host;
            this.database = database;
            this.port = port;
        }
           // Getters and setters
   }
}

application.yml
demo:
  archive:
  -
    host: "localhost"
    database: "archive1"
    port: "27017"
  -
    host: "localhost"
    database: "archive2"
    port: "27017" 

显示异常

Binding to target [Bindable@129425f type = java.util.List<com.example.demo.config.Democonfig$Archive>, value = 'provided', annotations = array<Annotation>[[empty]]] failed:

    Property: demo.archive[0].database
    Value: archive1
    Origin: class path resource [application.yml]:5:15
    Reason: The elements [demo.archive[0].database,demo.archive[0].host,demo.archive[0].port,demo.archive[1].database,demo.archive[1].host,demo.archive[1].port] were left unbound.
    Property: demo.archive[0].host
    Value: localhost
    Origin: class path resource [application.yml]:4:11
    Reason: The elements [demo.archive[0].database,demo.archive[0].host,demo.archive[0].port,demo.archive[1].database,demo.archive[1].host,demo.archive[1].port] were left unbound.
    Property: demo.archive[0].port
    Value: 27017

点击here! 完整的源代码和在git中上传的项目

1 个答案:

答案 0 :(得分:5)

只是在嵌套静态类中缺少No arg构造函数

public static class Archive {
    private String host;
    private String database;
    private String port;

    public Archive() {
        // TODO Auto-generated constructor stub
    }

    public Archive(String host, String database, String port) {
        System.out.println("constri=uu Archive");
        this.host = host;
        this.database = database;
        this.port = port;
    }
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public String getDatabase() {
        return database;
    }
    public void setDatabase(String database) {
        this.database = database;
    }
    public String getPort() {
        return port;
    }
    public void setPort(String port) {
        this.port = port;
    }
    @Override
    public String toString() {
        return "Archive [host=" + host + ", database=" + database + ", port=" + port + "]";
    }

}

实际上没有必要向构造函数提供参数。只有setter和getter可以使用。我也鼓励u签出并使用lombok,这将使您的代码更加简洁。