spring boot 获取yml配置文件里面配置项为null

spring boot 获取yml配置文件里面配置项

 

1> 引入 spring-boot-configuration-processor 库

    org.springframework.boot

    spring-boot-configuration-processor

    true

 

2> 在 application.yml 中要获取的数据

 

myprops:

  simpleProp: 8080

 

3> 使用 @ConfigurationProperties 将数据绑定到对象上

 

@Component

@ConfigurationProperties(prefix = "myprops")

public class MyProps {

private String simpleProp;

 public String getSimpleProp() {

        return simpleProp;

    }

   /**

    * String类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要

    *

    * @param simpleProp

    */

    public void setSimpleProp(String simpleProp) {

        this.simpleProp = simpleProp;

    }

}

4.之后就可以直接使用

@Autowired

private MyProps myProps;

 

@Test

public void propsTest() {

    System.out.println("simpleProp: " + myProps.getSimpleProp());

}

 

遇到的问题:

        在获取simpleProp的时候,值始终都是null。而不是8080.

解决:

1.检查拼写,可以驼峰---没问题。

2.检查前缀(prefix = "myprops")---没问题。

3.yml文件中格式。备注,yml格式会根据空格来判定树。所以一个独立的配置项,必须紧紧贴着左边框,不能 有空格。--我的问题所在。

如图。

spring boot 获取yml配置文件里面配置项为null_第1张图片

spring boot 获取yml配置文件里面配置项为null_第2张图片

你可能感兴趣的:(spring,boot)