SpringBoot實現(xiàn)給屬性賦值的兩種方式
一,介紹
在Spring Boot中,配置文件是用來設置應用程序的各種參數(shù)和操作模式的重要部分。Spring Boot支持兩種主要類型的配置文件:properties文件和YAML 文件。這兩種文件都可以用來定義相同的配置,但它們在格式和表達能力上有所不同。
二,Properties 配置方式
properties文件是Java平臺最傳統(tǒng)的配置方式,文件擴展名為 .properties。這種格式非常簡單,主要由鍵值對組成,每一對鍵值對設置一個配置屬性。
示例:
定義模型Person類:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="person")
public class Person {
private String name;
private int age;
private String uuid;
private Dog dog;
// standard getters and setters
public static class Dog {
private String name;
private String breed;
// standard getters and setters
}
}Properties 配置
person.name=John Doe
person.age=35
person.uuid=${random.uuid}
person.dog.name=Rex
person.dog.breed=Labrador這樣配置后,Spring Boot 會自動application.properties中的相關配置注入到 Person對象和其內(nèi)部的 Dog對象。
使用 @Value注解也可以直接在 Spring Boot 應用中注入配置值,例
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Person {
@Value("${person.name}")
private String name;
@Value("${person.age}")
private int age;
@Value("${person.uuid}")
private String uuid;
// 內(nèi)部類和其他配置略
}三,YAML 配置方式
YAML 是一種層次結構化的數(shù)據(jù)格式,相比于 properties文件,它支持列表和嵌套的對象,使得配置更加清晰和組織化。
yaml配置:
person:
name: "John Doe"
age: 35
uuid: ${random.uuid}
dog:
name: "Rex"
breed: "Labrador"這時要將YAML文件中的配置自動映射到一個Java類中,需要在Spring Boot應用中定義相應的配置類,并使用@ConfigurationProperties注解。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Configuration
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private int age;
private String uuid;
private Dog dog;
@Component
public static class Dog {
private String name;
private String breed;
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
}四,對比
1. 可讀性
- YAML 由于其支持層級結構,通常在表達更復雜的配置時更加清晰和易讀。
- Properties 文件更適合簡單的平面鍵值對,但在需要表達嵌套配置時可讀性較差。
2. 表達能力
- YAML 支持復雜的數(shù)據(jù)結構,如列表和字典(即嵌套的對象),這使得它在表達如安全規(guī)則、路由配置等復雜配置時非常有用。
- Properties 文件不支持直接的層級或復雜結構,所有結構都必須通過點分隔的方式平鋪開來表達。
3. 錯誤檢測
- YAML 文件由于格式更加復雜,對縮進非常敏感,錯誤的縮進可能導致整個文件無法解析。
- Properties 文件結構簡單,縮進和格式錯誤的容忍度較高。
4. 使用場景
- 如果配置較為簡單,或是遷移遺留項目而不希望引入新的復雜性,那么使用
.properties可能更合適。 - 對于新項目或需要表達復雜配置的情況,
.yaml提供了更強的表達能力和更好的可讀性。
以上就是SpringBoot實現(xiàn)給屬性賦值的兩種方式的詳細內(nèi)容,更多關于SpringBoot給屬性賦值的資料請關注腳本之家其它相關文章!
相關文章
java 出現(xiàn)問題javax.servlet.http.HttpServlet was not found解決方法
這篇文章主要介紹了java 出現(xiàn)問題javax.servlet.http.HttpServlet was not found解決方法的相關資料,需要的朋友可以參考下2016-11-11

