配置文件类型
SpringBoot的配置都有默认值,但也可以根据需要自定义配置
可以通过application.properties或者application.yml进行配置
这两个配置文件都在resources目录下,且properties的优先级高于yml
yml配置文件
yml容易阅读,容易和脚本语言交互,以数据为核心,比xml更简洁
yml 语法
key: value
value前有一个空格
示例1
age: 15
示例2
person:
name: Ding
age: 20
no: 43962200
等同于
person:{name: Ding,age: 20,no: 43962200}
在yml中,相同缩进表示同一级别
示例3 配置数组数据(List/set)
country:
- UK
- US
- CN
等同与
country:[UK,US,CN]
示例4
iG:
- id:The Shy
position: top
- id: Ning
position: jug
- id: Rookie
position: mid
- id: Jkl
position: ad
- id: Baolan
position: sup
注意value和 - 之间有一个空格
配置文件与配置类的属性映射方式
通过注解@Value映射
yml配置
Bean代码
package com.example.demo.contronler;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ConfigurationProperties(prefix = "people")
@Setter
public class BeanController {
@Value("${person.name}")
private String name1;
@Value("${person.age}")
private int age1;
@RequestMapping("/m4")
@ResponseBody
public String m4(){
return "name1:"+name1+"age1:"+age1;
}
}
访问http://localhost:8080/m4
通过注释@ConfigurationProperties映射
通过注释@ConfigurationProperties(prefix=“配置文件中key的前缀”)将文件中的配置与实体进行映射
yml文件配置
Bean1代码
package com.example.demo.contronler;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ConfigurationProperties(prefix = "people")
@Setter//需要安装lombook插件
public class Bean1Controller {
private String name;
private int age;
@RequestMapping("/m5")
@ResponseBody
public String m5(){
return "name:"+name+",age:"+age;
}
}
访问localhost:8080/m5