一. 配置文件作用
二. 配置文件的格式
1).properties(默认)
2).yml
注意:
1 .properties 配置文件的优先级最高,但加载完 .properties 文件之后,也会加载 .yml 文件的配置信息
2 虽然 .properties 可以和 .yml 共存,但实际的业务当中,我们通常会采取⼀种统⼀的配置文件格式,这样可以更好的维护(降低故障率)
三. properties 配置文件说明
3.1 properties 基本语法
# 使用 # 表示注释
# 配置项目端口号
server.port=8888
# 连接数据库
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
3.2 读取配置文件
在项目中使用 @Value(${}) 注解来主动读取配置文件中的内容
@Component
public class ReadYml {
@Value("${server.port}")
private String port;
@PostConstruct
public void postConstruct() {
System.out.println("Read YML,port:" + port);
}
}
3.3 properties 缺点分析
四. yml 配置文件说明
yml 优点分析:
1)yml 是⼀个可读性高,写法简单、易于理解,它的语法和 JSON 语言类似
2)yml 支持更多的数据类型
3)yml 支持更多的编程语言
4.1 yml 基本语法
yml 是树形结构的配置⽂件,它的基础语法是“key: value”,注意 key 和 value 之间使⽤英⽂冒汗加空格的⽅式组成的,其中的空格不可省略:
使用 yml 连接数据库
4.2 yml 使用进阶
4.2.1 yml 配置不同数据类型及 null
# 字符串
string.value: Hello
# 布尔值,true或false
boolean.value: true
boolean.value1: false
# 整数
int.value: 10
int.value1: 0b1010_0111_0100_1010_1110 # ⼆进制
# 浮点数
float.value: 3.14159
float.value1: 314159e-5 # 科学计数法
# Null,~代表null
null.value: ~
4.2.2 yml 配置读取
@Component
public class ReadYml {
@Value("${string.hello}")
private String hello;
@PostConstruct
public void postConstruct() {
System.out.println("Read YML,Hello:" + hello);
}
}
4.2.3 配置对象
在 yml 中配置对象:
student:
id: 1
name: 张三
age: 18
或使用行内写法:
student: {id: 1,name: 张三,age: 18}
这时需要使用 @ConfigurationProperties 来读取:
@Component
@ConfigurationProperties("student")
@Data
public class Student {
private int id;
private String name;
private int age;
}
@Component
public class test2 {
@Autowired
private Student student;
@PostConstruct
public void postConstruct() {
System.out.println(student);
}
}
4.2.4 配置集合
在 yml 中配置 list 集合
dbtypes:
name:
- mysql
- sqlserver
- db2
或使用行内写法:
dbtypes: {name: [mysql,sqlserver,db2]}
同样使用 @ConfigurationProperties 来读取:
@Component
@ConfigurationProperties("dbtypes")
@Data
public class ListConfig {
private List<String> name;
}
@Component
public class ReadYml2 {
@Autowired
private ListConfig listConfig;
@PostConstruct
public void postConstruct() {
System.out.println(listConfig.getName());
}
}
五. properties 和 yml 对比
1)properties 是以 key=value 的形式配置的键值类型的配置⽂件,⽽ yml 使⽤的是类似 json 格式的树形配置⽅式进⾏配置的,yml 层级之间使⽤换⾏缩进的⽅式配置,key 和 value 之间使⽤“: ”英⽂冒号加空格的⽅式设置,并且空格不可省略。
2)properties 为早期并且默认的配置⽂件格式,但其配置存在⼀定的冗余数据,使⽤ yml 可以很好的解决数据冗余的问题。
3)yml 通⽤性更好,⽀持更多语⾔。
4)yml ⽀持更多的数据类型。
六. 设置不同环境的配置文件