定义application.yml文件:

# 定义变量
name: abc

#引用变量
myname: ${name}

#对象的写法
person:
  name: zhangsan
  age: 20
  address:
    - beijing
    - shanghai

#对象的行内写法
person2: {name: lisi, age: 18}

#数组的写法
address:
  - beijing
  - shanghai

# 数组的行内写法
address2: [guangzhou, shenzhen]

#字符串:不会识别转义字符
msg1: 'hello \n world'

#字符串:自动识别转义字符
msg2: "hello \n world"

 

读取信息的方式:

 1 @Slf4j
 2 @RestController
 3 public class IndexController {
 4 
 5     @Value("${name}")
 6     private String Name;
 7 
 8     @Value("${person.name}")
 9     private String Name2;
10 
11     @Value("${address[0]}")
12     private String Address;
13 
14     @Value("${msg1}")
15     private String Msg1;
16 
17     @Value("${msg2}")
18     private String Msg2;
19 
20     @Autowired
21     private Environment environment;
22 
23     @Autowired
24     private Person person;
25 
26     @RequestMapping("/")
27     public String Index(){
28 
29         log.info("hello world");
30         return "hello world spring boot";
31     }
32 
33     @RequestMapping("/read")
34     public String Read(){
35         System.out.println(this.Name);
36         System.out.println(this.Name2);
37         System.out.println(this.Address);
38         System.out.println(this.Msg1);
39         System.out.println(this.Msg2);
40 
41         System.out.println("---------------------");
42 
43         System.out.println(environment.getProperty("person2.age"));
44         System.out.println(environment.getProperty("address2[1]"));
45 
46         System.out.println("----------------------");
47 
48         System.out.println(person.toString());
49         return "";
50     }
51 }

 

使用ConfigurationProperties将yml文件中的一个节绑定到对象上:

 1 @Data
 2 @ToString
 3 @NoArgsConstructor
 4 @AllArgsConstructor
 5 @Component
 6 @ConfigurationProperties("person")
 7 public class Person {
 8     private String Name;
 9     private Integer Age;
10     private String[] Address;
11 }

 

posted on 2021-10-24 01:34  Sempron2800+  阅读(207)  评论(0编辑  收藏  举报