• Spring Boot学习05YAML数据配置与使用


    定义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 }
  • 相关阅读:
    3503: [Cqoi2014]和谐矩阵
    2734: [HNOI2012]集合选数
    P3900 [湖南集训]图样图森破
    4557: [JLoi2016]侦察守卫
    牛客OI周赛6-提高组 B 践踏
    连续区间的最大公约数
    Wannafly挑战赛5 D. 子序列
    牛客国庆集训派对Day1 B. Attack on Titan
    4538: [Hnoi2016]网络
    [SHOI2015]超能粒子炮·改
  • 原文地址:https://www.cnblogs.com/asenyang/p/15450156.html
Copyright © 2020-2023  润新知