SpringBoot配置-读取YAML配置来获取数据

文章目录

  • 一、YAML配置文件
  • 二、读取YAML配置内容
    • 1.方法一:@Value
    • 2.方法二:Enviroment
    • 3.方法三:@ConfigurationProperties


一、YAML配置文件

代码如下(示例):

#修改端口号
server:
  port: 8083


#对象
person:
  name: lisi
  age: 20

#数组
address:
  - beijing
  - shanghai

#纯量
msg: "Hello \n SpringBoot"

二、读取YAML配置内容

1.方法一:@Value

代码如下(示例):

@RestController
public class SpringBootController {
    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private int age;
    @Value("${address[0]}")
    private String address1;
    @Value("${msg}")
    private String msg;
@RequestMapping("/hello")
    public String Hello(){
        System.out.println(name);
        System.out.println(age);
        System.out.println(address1);
        System.out.println(msg);
     return "SpringBoot";
    }
 }

2.方法二:Enviroment

代码如下(示例):

@RestController
public class SpringBootController {
 @Autowired
    private Environment env;
    @RequestMapping("/hello")
    public String Hello(){
        System.out.println(env.getProperty("person.name"));
        System.out.println(env.getProperty("address[0]"));
        System.out.println(env.getProperty("msg"))
        return "SpringBoot";
    }
  }

3.方法三:@ConfigurationProperties

代码如下(示例):

//编写实体类
@Component //被Spring识别
@ConfigurationProperties(prefix = "person")

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
@RestController
public class SpringBootController {
 @Autowired
    private Person person ;
    @RequestMapping("/hello")
    public String Hello(){
        System.out.println(person);
        return "Hello SpringBoot";
    }
  }

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