配置文件
SpringBoot 有兩種配置文件格式,二選一即可,官方推薦 yaml:
- application.properties key=value的格式
- application.yaml key: value的格式
配置文件位置
SpringBoot會從這四個位置全部加載主配置文件;互補配置。優先級從高到低。
- --spring.config.location=F:/application.yaml
- /config/application.yaml
- /application.yaml
- /src/main/resources/config/application.yaml
- /src/main/resources/application.yaml
yaml 格式特點
- 冒號后面必須有一個空格,不能省略
- 以縮進來控制層級關系,左邊對齊的為同一層級
- 屬性和值的大小寫敏感
- 雙引號中的特殊字符會轉義輸出,如"hello \n world"會發生換行
- 雙引號中的特殊字符會原樣輸出,如‘hello \n world’所見即所得
配置示例
# src/main/resources/application.properties
server.port=8081
# src/main/resources/application.yaml
server:
port: 8081
# 對象形式
student:
name: zhangsan
age: 18
# 行內對象形式
student: {name: zhangsan,age: 18}
# 數組形式
pets:
- cat
- dog
- pig
# 行內數組形式
pets: [cat,dog,pig]
配置 banner
# src/main/resources/banner.txt
# https://www.bootschool.net/ascii-art
_ _
_(9(9)__ __/^\/^\__
/o o \/_ __\_\_/\_/_/_
\___, \/_ _\.' './_ _/\_
`---`\ \/_ _\/ \/_ _|.'_/
\ \/_\/ / \/_ |/ /
\ `-' | ';_:' /
/| \ \ .'
/_/ |,___.-`', /`'---`
/___/` /____/
注入 yaml 配置文件(方式一)
package com.wu.helloworld.pojo;
@Component
public class Dog {
@Value("阿黃")
private String name;
@Value("18")
private Integer age;
}
@SpringBootTest
class HelloworldApplicationTests {
@Autowired
private Dog dog;
@Test
public void contextLoads() {
System.out.println(dog)
}
}
注入 yaml 配置文件(方式二)
<!-- 導入配置文件處理器依賴,需要重啟IDE -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
package com.wu.helloworld.pojo;
@Component
public class Dog {
private String name;
private Integer age;
//構造函數、get、set、toString 等方法
}
@Component
@ConfigurationProperties(prefix = "person")
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;
//構造函數、get、set、toString 等方法
}
person:
name: wu_${random.uuid}
age: ${random.int}
happy: false
birth: 2000/01/01
maps: {k1: v1,k2: v2}
lists:
- code
- girl
- music
dog:
name: ${person.dogName:默認名字}_旺財
age: 1
@SpringBootTest
class DemoApplicationTests {
@Autowired
Person person;
@Test
public void contextLoads() {
System.out.println(person);
}
}
注入 properties 配置文件
設置 properties 的編碼格式為UTF-8:
File / Settings / File Encodings / Properties Files / UTF-8 && √ Transparent native-to-ascii conversion
# src/main/resources/person.properties
person.name=wu
person.age=18
person.sex=男
// 使用 PropertySource 注解加載制定的配置文件
@PropertySource(value = "classpath:person.properties")
@Component
public class Person {
@Value("${person.name}") // 從配置文件中取值
private String name;
@Value("#{9*2}") // #{SPEL} Spring表達式
private int age;
@Value("男") // 字面量
private String sex;
}
松散綁定
dog:
first-name: 旺財
age: 3
@Component
@ConfigurationProperties(prefix = "dog")
public class Dog {
private String firstName; // 可以綁定橫杠的配置值
private Integer age;
}