SpringBoot学习笔记——配置文件

目录

1、文件类型

2、yaml语法

2.1、基本语法

2.2、数据类型

2.3、配置提示


1、文件类型

配置文件分为两种:

  • application.properties
  • application.yaml

书写格式:

application.properties

SpringBoot学习笔记——配置文件_第1张图片

application.yaml(也可以写成application.yml)

SpringBoot学习笔记——配置文件_第2张图片

2、yaml语法

2.1、基本语法

  • key: value;kv之间有空格
  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进不允许使用tab,只允许空格
  • 缩进的空格数不重要,只要相同层级的元素左对齐即可
  • '#'表示注释
  • 字符串无需加引号,如果要加,''与""表示字符串内容 会被 转义/不转义

2.2、数据类型

  • 字面量:单个的、不可再分的值。date、boolean、string、number、null
k: v
  • 对象:键值对的集合。map、hash、set、object
行内写法:  k: {k1:v1,k2:v2,k3:v3}
#或
k: 
  k1: v1
  k2: v2
  k3: v3
  • 数组:一组按次序排列的值。array、list、queue
行内写法:  k: [v1,v2,v3]
#或者
k:
 - v1
 - v2
 - v3

实例: 

Person类

@ConfigurationProperties(prefix = "person")
@Component
@Data
@ToString
public class Person {
	
	private String userName;
	private Boolean boss;
	private Date birth;
	private Integer age;
	private Pet pet;
	private String[] interests;
	private List animal;
	private Map score;
	private Set salarys;
	private Map> allPets;
}

Pet类

@Data
@ToString
public class Pet {
	private String name;
	private Double weight;
}

application.yaml文件

  • 单引号会将 \n 作为字符串输出,双引号会将 \n 作为换行输出
    
  • 双引号不会转义,单引号会转义
person:
  userName: zhangsan
  boss: false
  birth: 2019/12/12 20:12:33
  age: 18
  pet: 
    name: tomcat
    weight: 23.4
  interests: [篮球,游泳]
  animal: 
    - jerry
    - mario
  score:
    english: 
      first: 30
      second: 40
      third: 50
    math: [131,140,148]
    chinese: {first: 128,second: 136}
  salarys: [3999,4999.98,5999.99]
  allPets:
    sick:
      - {name: tom}
      - {name: jerry,weight: 47}
      - name: lucy
        weight: 12
    health: [{name: mario,weight: 47}]

在controller文件下的HelloController类中添加以下代码

@Autowired
Person person;

@RequestMapping("/person")
public Person person(){
    return person;
}

运行main函数,查看结果

SpringBoot学习笔记——配置文件_第3张图片

2.3、配置提示

在pom.xml文件中加入以下依赖,在编写application.yaml文件的时候就会有自动提示


    org.springframework.boot
    spring-boot-configuration-processor
    true

SpringBoot2学习笔记 

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