如何从Spring-boot应用程序中的application.yml文件读取属性

时间:2019-09-22 09:14:10

标签: java spring-boot

我的应用程序具有嵌套属性,该属性存储在applicaion.yml文件中。
我想在应用程序启动时将这些属性映射到 POJO

Application.yml

    demo:
     - A:
       - type: A
         prop1: 1
         prop2: 2
         proop3: 3
       - type: B
         prop1: 1
         prop2: 2
         proop3: 3
     - B:
       - type: A
         prop1: 1
         prop2: 2
         proop3: 3
       - type: B
         prop1: 1
         prop2: 2
         proop3: 3

为了实现这一点,我使用以下注释:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(“ demo”)

班级演示:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("demo")
public class Demo {
    @JsonProperty("A")
    private List<A> a = null;
    @JsonProperty("B")
    private List<B> b = null;

    @JsonProperty("A")
    public List<A> getA() {
        return a;
    }

    @JsonProperty("A")
    public void setA(List<A> a) {
        this.a = a;
    }

    @JsonProperty("B")
    public List<B> getB() {
        return b;
    }

    @JsonProperty("B")
    public void setB(List<B> b) {
        this.b = b;
    }

    @Override
    public String toString() {
        return "Demo [a=" + a + ", b=" + b + "]";
    }   
}



A类:

public class A {

    @JsonProperty("type")
    private String type;
    @JsonProperty("prop1")
    private Integer prop1;
    @JsonProperty("prop2")
    private Integer prop2;
    @JsonProperty("proop3")
    private Integer proop3;

    @JsonProperty("type")
    public String getType() {
        return type;
    }

    @JsonProperty("type")
    public void setType(String type) {
        this.type = type;
    }

    @JsonProperty("prop1")
    public Integer getProp1() {
        return prop1;
    }

    @JsonProperty("prop1")
    public void setProp1(Integer prop1) {
        this.prop1 = prop1;
    }

    @JsonProperty("prop2")
    public Integer getProp2() {
        return prop2;
    }

    @JsonProperty("prop2")
    public void setProp2(Integer prop2) {
        this.prop2 = prop2;
    }

    @JsonProperty("proop3")
    public Integer getProop3() {
        return proop3;
    }

    @JsonProperty("proop3")
    public void setProop3(Integer proop3) {
        this.proop3 = proop3;
    }

    @Override
    public String toString() {
        return "A [type=" + type + ", prop1=" + prop1 + ", prop2=" + prop2 + ", proop3=" + proop3 + "]";
    }
}



B类

public class B {

    @JsonProperty("type")
    private String type;
    @JsonProperty("prop1")
    private Integer prop1;
    @JsonProperty("prop2")
    private Integer prop2;
    @JsonProperty("proop3")
    private Integer proop3;

    @JsonProperty("type")
    public String getType() {
        return type;
    }

    @JsonProperty("type")
    public void setType(String type) {
        this.type = type;
    }

    @JsonProperty("prop1")
    public Integer getProp1() {
        return prop1;
    }

    @JsonProperty("prop1")
    public void setProp1(Integer prop1) {
        this.prop1 = prop1;
    }

    @JsonProperty("prop2")
    public Integer getProp2() {
        return prop2;
    }

    @JsonProperty("prop2")
    public void setProp2(Integer prop2) {
        this.prop2 = prop2;
    }

    @JsonProperty("proop3")
    public Integer getProop3() {
        return proop3;
    }

    @JsonProperty("proop3")
    public void setProop3(Integer proop3) {
        this.proop3 = proop3;
    }

    @Override
    public String toString() {
        return "B [type=" + type + ", prop1=" + prop1 + ", prop2=" + prop2 + ", proop3=" + proop3 + "]";
    }
}



主班

@SpringBootApplication
@ComponentScan(basePackages = {"com.microservice.*"})
@EnableJpaRepositories("com.microservice.*")
@EntityScan("com.microservice.*")
public class MainApplication {  
    public static void main(String[] args) {
         SpringApplication app = new SpringApplication(MainApplication.class);
            app.run();
            System.out.println("step 1");
            Demo config = new Demo();
            System.out.println("name: " + config);
        }

        public void run(String... args) throws Exception {
            System.out.println("step 2");

        }
}

但是我低于o / p:
第1步
名称:演示[a = null,b = null]

4 个答案:

答案 0 :(得分:3)

当您手动创建即时属性POJO时,Spring对此一无所知,并且不会进行属性绑定。

 SpringApplication app = new SpringApplication(MainApplication.class);
    app.run();
    System.out.println("step 1");
    Demo config = new Demo(); // Not a Spring managed bean!
    System.out.println("name: " + config);
}

您可以使@EnableConfigurationProperties成为bean,而不是用Demo注释配置,如Type-safe Configuration Properties所示。

@Component
@ConfigurationProperties("demo")
public class Demo {
    ...
}

然后您可以从上下文中获得Demo bean:

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
        Demo demo = (Demo) context.getBean("demo");
        System.out.println(demo.getName());
    }
}

UPD :在“ a”和“ b”之前不能有连字符:

demo:
  a:
    - type: A
      prop1: 1
      prop2: 2
      proop3: 3
    - type: B
      prop1: 1
      prop2: 2
      proop3: 3
  b:
    - type: B
      prop1: 1
      prop2: 2
      proop3: 3

UPD2:回答评论。您可以使用DemoObjectMapper bean构建JSON:

@SpringBootApplication
public class MainApplication {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

    public static void main(String[] args) throws JsonProcessingException {
        ...
        ObjectMapper objectMapper = (ObjectMapper) context.getBean("objectMapper");
        System.out.println(objectMapper.writeValueAsString(demo));
    }
}

使用spring-boot-starter-web,不需要其他依赖项。否则,您可以添加jackson

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.0.1</version>
</dependency>

答案 1 :(得分:1)

在您的yml文件中这是错误的。您可以在此处Merging YAML listslink上读取参考。

我编写了一个演示,它可以工作。

demo:
        a:
            b:
                prop1: prop1
                prop2: prop2
            blist:
                - prop1: prop1
                  prop2: prop2
        alist:
            - b:
                  prop1: prop1
                  prop2: prop2
              blist:
                  - prop1: prop1
                    prop2: prop2
            - b:
                  prop1: prop1
                  prop2: prop2

``

@ConfigurationProperties(prefix = "demo")
public class Demo {
    private A a;
    private List<A> alist;
    // omitted getter/setter
}

``

public class A {
    private B b;
    private List<B> blist;
    // omitted getter/setter
}

``

public class B {
    private String prop1;
    private String prop2;
    // omitted getter/setter
}

答案 2 :(得分:0)

如果您想从.yml.properties文件中读取属性,我建议您创建一个可以称为PropertiesBooter的类,在该类中,您将从这些文件中检索所有值文件。要从属性文件中检索值,您可以编写

@Value("${value}")
private String 

答案 3 :(得分:0)

从米哈伊尔(Mikhail)答案中,只需使用杰克逊ObjectMapper编写json,您就会获得json格式:

public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(YamlTestApplication.class, args);
        Demo demo = (Demo) context.getBean("demo");
        System.out.println("name: " + demo);

        ObjectMapper mapper = new ObjectMapper();
        try {
            String test = mapper.writeValueAsString(demo);
            System.out.println("json: "+test);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

输出:

name: Demo [a=[A [type=A, prop1=1, prop2=2, proop3=3], A [type=B, prop1=1, prop2=2, proop3=3]], b=[B [type=A, prop1=1, prop2=2, proop3=3], B [type=B, prop1=1, prop2=2, proop3=3]]]
json: {"A":[{"type":"A","prop1":1,"prop2":2,"proop3":3},{"type":"B","prop1":1,"prop2":2,"proop3":3}],"B":[{"type":"A","prop1":1,"prop2":2,"proop3":3},{"type":"B","prop1":1,"prop2":2,"proop3":3}]}