springboot配置文件
配置文件的几种后缀
<resource>
<directory>${basedir}/src/main/resources</directory>
<excludes>
<exclude>**/application*.yml</exclude>
<exclude>**/application*.yaml</exclude>
<exclude>**/application*.properties</exclude>
</excludes>
</resource>
对应的语法结构
springboot使用一个全局的配置文件,配置文件名称是固定的
- application.properties
语法结构:key=value - application.yml/application.yaml
语法结构: key: 空格 value
配置文件的作用
修改springboot自动配置的默认值,因为springboot在底层都给我们配置好了。
一些基本用法
# 普通的key-value
name: Haley
# 对象
student1:
name: Haley
age: 20
# 行内写法
student2: {name: Haley,age: 20}
# 数组
pets1:
- cat
- dog
- pig
pets2: [cat,dog,pig]
给实体类赋值的几种方法
1. 直接赋值
- 实体类
@Component
@Data
public class Dog {
@Value("旺财")
private String name;
@Value("3")
private Integer age;
}
- 测试
@SpringBootTest
class NginxApplicationTests {
@Autowired
private Dog dog;
@Test
void contextLoads() {
System.out.println(dog);
}
}
- 结果
2. 通过配置文件赋值
- 同时给多个变量赋值
person:
name: Haley
age: 20
happy: false
birth: 2019/11/02
maps: {k1: v1,k2: v2}
lists: [code,music,pet]
dog:
name: 旺财
age: 3
@Component
@Data
@ConfigurationProperties(prefix = "person")//使用@ConfigurationProperties
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
@SpringBootTest
class NginxApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);//打印person,查看是否赋值成功
}
}
- 给单个变量赋值
@Component
@Data
public class Dog {
@Value("${name}")
private String name;
@Value("${age}")
private Integer age;
}
配置文件的位置
优先级:①>④>②>③