SpringBoot核心配置
- 本文主要讲述:
- yml和properties配置文件语法区别
- 使用@ConfigurationProperties全局配置,@value提取部分配置
- @PropertySource 加载局部配置文件定义局部配置文件
- profile实现多环境支持
Spring Boot 使用一个全局配置文件,放置在 src/main/resources 目录或类路径的 /config 下;
配置文件的作用:
修改springboot自动配置的默认值;
yml不是标记语言;
标记语言:
以前的配置文件;大多都使用的是 xxxxx.xml文件;
<server>
<port>8080</8080>
</server>
yml:
以数据为中心,配置数据的时候具有面向对象的特征;比 json、xml 等更适合做配置文件;
server:
port: 8080
注意:必须进行换行,并且冒号后面必须有空格
2.YAML配置文件格式:
2.1 YAML基本语法
- key: value 表示一对键值对(冒号后面必须要有空格)
- 使用空格缩进表示层级关系;
- key和value大小写敏感;
server:
port: 8080
2.2 YAML常用写法
字面量:数值,字符串,布尔,日志
字符串:默认不加引号;
不会转义特殊字符,特殊字符最终会转成本来想表示含义输出
name: “mengxuegu \n jiaoyu” 输出: mengxuegu 换行 jiaoyu
会转义特殊字符,特殊字符当作一个普通的字符串输出
name: 'mengxuegu \n jiaoyu 输出: mengxuegu \n ji
emp:
lastName: xiaomeng
age: 22
salary: 1000
对象&Map
key: value value存储对象,每个值换一行写,注意值要左对齐
map:
key1: value1
key2: value2
forte:
name: java
time: 2
数组List,Set
用 - 表示数组中的一个元素
list:
-one
-two
-three
3.YAML配置文件注入法
3.1 编javaBean
bean目录下创建Emp.java
/**
* 1、@ConfigurationProperties 告诉SpringBoot将配置文件中对应属性的值,映射到这个组件类中,进
行一一绑定
* prefix = "emp":配置文件中的前缀名,哪个前缀与下面的所有属性进行一一映射
* 2、@Component 必须将当前组件作为SpringBoot中的一个组件,才能使用容器提供的
@ConfigurationProperties功能;
*
* @Auther: www.mengxuegu.com
*/
@Component
@ConfigurationProperties(prefix = "emp")
public class Emp {
private String lastName;
private Integer age;
private Double salary;
private Boolean boss;
private Date birthday;
private Map map;
private List list;
//特长
private Forte forte;
getter/setter……
}
public class Forte {
private String name;
private Integer time;
getter/setter……
}
3.2 编写 application.yml 配置文件
emp:
lastName: zhangsan
age: 28
salary: 20000
boss: true
birthday: 1991/10/10
map:
key1: value1
key2: value2
list:
- one
- two
- three
forte:
name: java
time:2
3.3 使用 SpringBoot 单元测试类进行测试
/**
* SpringBoot单元测试:
* 在测试时,可以直接将对象注入到容器中使用
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {
@Autowired
Emp emp;
@Test
public void contextLoads() {
System.out.println(emp);
}}
导入配置文件处理器,然后重新运行测试类,在编写配置文件时就会提示
<!--导入配置文件处理器,在编写配置文件时就会提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
4. properties 配置文件注入值
编写 application.properties 配置文件
#配置emp的值
emp.last-name=李四
emp.age=30
emp.birthday=1989/9/12
emp.boss=false
emp.salary=23000
emp.map.key1=value1
emp.map.key2=value2
emp.list=one, two, three
emp.forte.name=python
emp.forte.time=3
运行后,发现 properties 文件在 idea 上中文乱码, 进行如下设置就会不会乱码