Java所用相關軟體的大致安裝流程
阿新 • • 發佈:2022-04-16
-
application.properties 語法 key=value
-
application.yaml 語法 key: 空格 value
配置檔案的作用是修改自動配置的值
yaml是一種標記語言(與xml對比)
server:
prot: 8080
xml:
<server>
<prot>8080<prot/>
<server/>
yaml與properties對比
yaml:
#yaml對於空格的使用比較嚴格 #可以注入到配置類中 #普通k-v鍵值對 name: xiaoming #物件 people: name: xiaoming age: 11 #行內寫法 person: {name: xiaoming, age: 11} #陣列 pets: - dog - cat - pig pets1: [dag,cat,pig]
properties:
#只能儲存k-v鍵值對
name=xiaoming
student.name = xiaoming
student.age = 11
給一個類的屬性賦值:
-
new這個類的物件,通過物件賦值
-
spring 自動注入@Value
@Component//將Dog類設定為元件 public class Dog { //@Value("CAL")//設定屬性值 private String name; //@Value("23") private Integer age;
-
yaml配置檔案
yaml檔案:
person: name: cal age: 23 happy: false birthday: 1999/06/06 maps: {k1: v1,k2: v2} lists: - lsp - sb - sd dog: name: dongdong age: 2
實體類:
@Component
@ConfigurationProperties(prefix = "person")//將實體類與配置檔案繫結
在pom.xml中新增依賴,即可解決
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</ optional> </dependency>
4.properties檔案
可能會亂碼,需要先修改設定
實體類:
@Component
//@ConfigurationProperties(prefix = "person")//將實體類與配置檔案繫結,預設從全域性配置檔案中獲取值;
@PropertySource(value = "classpath:zkh.properties")//從指定配置檔案中獲取值
public class Person {
//springEL表示式取值
@Value("${name}")
private String name;
}
在resources目錄下新建zkh.properties檔案
name=zkh
配置檔案佔位符:
person:
name: ${random.uuid} #隨機uuid
age: ${random.int}
happy: false
birthday: 1999/06/06
maps: {k1: v1,k2: v2}
lists:
- lsp
- sb
- sd
dog:
name: ${person.hello:other}dog #有person.hello則為person.hello的值,沒有則為other
age: 23
yaml支援鬆散繫結:
鬆散繫結: 比如yml中寫的fist-name,這個和實體類屬性fistName是一樣的, - 後面跟著的字母預設是大寫的。這就是鬆散繫結。
JSR303校驗:給實體類某一屬性設定對應的格式
@NotNull(message="名字不能為空")
private String userName;
@Max(value=120,message="年齡最大不能查過120")
private int age;
@Email(message="郵箱格式錯誤")
private String email;
空檢查
@Null 驗證物件是否為null
@NotNull 驗證物件是否不為null, 無法查檢長度為0的字串
@NotBlank 檢查約束字串是不是Null還有被Trim的長度是否大於0,只對字串,且會去掉前後空格.
@NotEmpty 檢查約束元素是否為NULL或者是EMPTY. Booelan檢查
@AssertTrue 驗證 Boolean 物件是否為 true
@AssertFalse 驗證 Boolean 物件是否為 false
長度檢查
@Size(min=, max=) 驗證物件(Array,Collection,Map,String)長度是否在給定的範圍之內
@Length(min=, max=) string is between min and max included.
日期檢查
@Past 驗證 Date 和 Calendar 物件是否在當前時間之前
@Future 驗證 Date 和 Calendar 物件是否在當前時間之後
@Pattern 驗證 String 物件是否符合正則表示式的規則
@Component //註冊bean@ConfigurationProperties(prefix = "person")
@Validated //資料校驗
public class Person {
@Email(message="郵箱格式錯誤") //name必須是郵箱格式
private String name;
}
配置檔案的位置及其優先順序:
切換配置檔案:
(1)properties
application-dev.properties 代表開發環境
application-test.properties 代表測試環境
只需在application.properties檔案中 寫入spring.profiles.active=dev 即可啟用對應的環境
(2)yaml
server:
port: 8080
spring:
profiles:
active: dev
---
server:
port: 8081
spring:
profiles: dev
---
server:
port: 8082
spring:
profiles: test