1. 將yml配置文件中的屬性轉換爲bean,註解@ConfigurationProperties
首先我們在yml中定義好內容:
student:
name: 張三
parents:
- 父親
- 母親
grades:
語文: 92
數學: 98
英文: 94
然後定義一個類Student:
@Component
//默認從application.yml中去讀取,但是我們還能指定yml文件,@PropertySource指定文件即可
@ConfigurationProperties(prefix = "student")
public class Student{
public String name;
//@Value("${student.name}") 默認情況下,屬性名字相同即可,如果名字不相同,可以用value註解
//public String myName;
public String[] parents;
//public LinkedList parents; list類型也行
public HashMap<String, String> grades;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setParents(String[] parents){
this.parents = parents;
}
public String[] getParents(){
return this.parents;
}
public void setGrades(HashMap<String, String> grades){
this.grades = grades;
}
public HashMap<String, String> getGrades(){
return this.grades;
}
}
此時,Student bean已經初始化好了,內容也有了,可以使用
public class Test{
@Autowired
public Student student;
public static void main(String[] args){
Test t = new Test();
System.out.println("學生的姓名是:" + t.student.getName());
}
}
來將student對象注入spring容器中,,然後直接可以用了。
2. @Validated 校驗
這個註解用於對參數進行校驗,那怎麼校驗呢,校驗那些數據呢?
假設有個Student類:
public class Student{
@NotEmpty
public String name;
@Max(150)
@Min(0)
public int age;
@Past
public Date birth;
}
在controller層有個方法:
@PostMapping("/createStudent")
public String setDeviceEnable(RequestBody @Validated Student student) {
return "創建完畢";
}
這個例子可以理解了,當用戶請求創建一個學生時,上傳一個學生對象student,student被聲明爲@Validated,說明要對這個對象進行校驗,將Student類中被聲明瞭校驗註解的變量全部檢查一遍,看是否合格,如果不合格,就返回用戶錯誤信息。
怎麼檢驗呢?有多種校驗註解,每種註解都對應一種校驗,如下:
@Null | 限制只能爲null |
@NotNull | 限制必須不爲null |
@AssertFalse | 限制必須爲false |
@AssertTrue | 限制必須爲true |
@DecimalMax(value) | 限制必須爲一個不大於指定值的數字 |
@DecimalMin(value) | 限制必須爲一個不小於指定值的數字 |
@Digits(integer,fraction) | 限制必須爲一個小數,且整數部分的位數不能超過integer,小數部分的位數不能超過fraction |
@Future | 限制必須是一個將來的日期 |
@Max(value) | 限制必須爲一個不大於指定值的數字 |
@Min(value) | 限制必須爲一個不小於指定值的數字 |
@Past | 限制必須是一個過去的日期 |
@Pattern(value) | 限制必須符合指定的正則表達式 |
@Size(max,min) | 限制字符長度必須在min到max之間 |
@Past | 驗證註解的元素值(日期類型)比當前時間早 |
@NotEmpty | 驗證註解的元素值不爲null且不爲空(字符串長度不爲0、集合大小不爲0) |
@NotBlank | 驗證註解的元素值不爲空(不爲null、去除首位空格後長度爲0),不同於@NotEmpty,@NotBlank只應用於字符串且在比較時會去除字符串的空格 |
驗證註解的元素值是Email,也可以通過正則表達式和flag指定自定義的email格式 |
3. 彩色日誌輸出
springboot 可以設置打印出彩色日誌。在yml中配置即可:
spring:
output:
ansi:
enabled: DETECT #NEVER 默認值,表示禁止彩色日誌;DETECT (推薦使用)表示檢查終端是否支持彩色日誌,如果支持纔開啓,如果不支持,就不開啓;ALWAYS表示不管終端是否支持,總是開啓,可能出現不正常的日誌現象
日誌級別和顏色的對應關係:
FATAL—— Red
ERROR ——Red
WARN ——Yellow
INFO ——Green
DEBUG ——Green
TRACE ——Green