欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot中yml的數(shù)據(jù)綁定示例

 更新時(shí)間:2023年11月22日 11:45:05   作者:zhizhiqiuya  
本文主要介紹了SpringBoot中yml的數(shù)據(jù)綁定示例,借助于YAML的簡(jiǎn)潔語(yǔ)法和結(jié)構(gòu)化特性,我們能夠輕松地管理應(yīng)用程序的配置信息,使得配置文件更加清晰易讀,感興趣的可以了解一下

前言

Spring Boot 提供了強(qiáng)大的配置能力,通過 YAML 文件進(jìn)行數(shù)據(jù)綁定是一種常見且便捷的方式。在本示例中,我們將演示如何利用 Spring Boot 的特性,通過 YAML 文件實(shí)現(xiàn)數(shù)據(jù)綁定。借助于 YAML 的簡(jiǎn)潔語(yǔ)法和結(jié)構(gòu)化特性,我們能夠輕松地管理應(yīng)用程序的配置信息,使得配置文件更加清晰易讀。通過本示例,您將了解如何利用 Spring Boot 快速、高效地實(shí)現(xiàn) YAML 數(shù)據(jù)綁定,為您的應(yīng)用程序提供靈活且可維護(hù)的配置管理。讓我們開始吧,深入探索 Spring Boot 中 YAML 數(shù)據(jù)綁定的精髓!

一、前期準(zhǔn)備

1、新建項(xiàng)目,結(jié)構(gòu)如下

2、導(dǎo)入依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.17</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>edu.nf</groupId>
    <artifactId>ch03</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ch03</name>
    <description>ch03</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latest</builder>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 這是一個(gè) Maven 的 pom.xml 文件,它描述了一個(gè) Spring Boot 項(xiàng)目的依賴關(guān)系和構(gòu)建方式。

在這個(gè)文件中,我們定義了兩個(gè)依賴項(xiàng):

spring-boot-starter:這是一個(gè) Spring Boot 的核心依賴,它包含了 Spring MVC、Spring Data JPA、Spring Security 等常用模塊,并且自動(dòng)配置了這些模塊所需的環(huán)境。通過引入這個(gè)依賴,我們可以快速搭建一個(gè)基于 Spring Boot 的 Web 應(yīng)用程序。

spring-boot-starter-test:這是一個(gè) Spring Boot 的測(cè)試依賴,它提供了許多用于測(cè)試的工具和框架,例如 JUnit、Mockito、Hamcrest 等。通過引入這個(gè)依賴,我們可以輕松地編寫和執(zhí)行單元測(cè)試和集成測(cè)試。

此外,我們還定義了一個(gè) Maven 插件 spring-boot-maven-plugin,用于將應(yīng)用程序打包成一個(gè)可執(zhí)行的 JAR 文件,以便于部署和運(yùn)行。在這個(gè)插件中,我們還可以配置容器、端口等參數(shù),以滿足不同的應(yīng)用程序需求。

總之,pom.xml 文件是 Spring Boot 項(xiàng)目的配置文件,它定義了項(xiàng)目的依賴關(guān)系和構(gòu)建方式,并且通過 Maven 插件實(shí)現(xiàn)了對(duì)應(yīng)用程序的打包和部署

二、第一種,值綁定

值綁定,使用 @value 注解精確指定節(jié)點(diǎn)的名稱

1、新建一個(gè) Student 類

@Component
@Data
public class Student {
    // 使用 @Value 注解和spell表達(dá)式將yml的節(jié)點(diǎn)值綁定到類的字段上
    @Value("${student.userId}")
    private Integer stuId;
    @Value("${student.userName}")
    private String stuName;
    @Value("${student.age}")
    private Integer age;
}

 這段代碼是一個(gè)Spring組件,用于將YAML配置文件中的值映射到Java對(duì)象的字段上。

首先,使用了@Data注解,它會(huì)自動(dòng)生成getter和setter方法、equals方法、hashCode方法以及toString方法。

然后,通過@Value注解來綁定YAML配置文件中的各個(gè)節(jié)點(diǎn)值到類的字段上。@Value注解中的"${student.userId}"等,是SpEL表達(dá)式,它會(huì)在運(yùn)行時(shí)從YAML配置文件中讀取對(duì)應(yīng)節(jié)點(diǎn)的值,并將其賦值給類的字段。

例如,如果在YAML配置文件中有以下內(nèi)容:

student:
 userId: 1001
 userName: qiu
 age: 18

那么在運(yùn)行時(shí),Student對(duì)象的stuId字段將被賦值為123,stuName字段將被賦值為"tom",age字段將被賦值為18。

總之,這段代碼可以讓你輕松地將YAML配置文件中的值映射到Java對(duì)象的字段上,方便你的代碼使用。

2、測(cè)試

@SpringBootTest
@Slf4j
class Ch03ApplicationTests {

    @Autowired
    private Student student;

    @Test
    void contextLoads() {
        log.info(student.getStuId().toString());
        log.info(student.getStuName());
        log.info(student.getAge().toString());
    }

}

這段代碼是一個(gè)Spring Boot的測(cè)試類,用于測(cè)試應(yīng)用程序的上下文加載和配置是否正確。

首先,使用了@SpringBootTest注解,它表示這是一個(gè)Spring Boot的集成測(cè)試類。它會(huì)自動(dòng)加載應(yīng)用程序的上下文,并進(jìn)行必要的配置。

然后,使用@Slf4j注解,它是Lombok庫(kù)提供的注解,可以自動(dòng)生成日志變量log。

接下來,通過@Autowired注解將Student對(duì)象注入到測(cè)試類中的student字段上。這樣就可以在測(cè)試方法中使用該對(duì)象。

在contextLoads()方法中,通過調(diào)用student對(duì)象的getter方法,獲取并打印stuId、stuName和age字段的值。這主要用于驗(yàn)證是否成功將YAML配置文件中的值綁定到Student對(duì)象的相應(yīng)字段上。

通過日志輸出,你可以在測(cè)試運(yùn)行時(shí)查看stuId、stuName和age字段的值。

總結(jié)起來,這段代碼用于測(cè)試Spring Boot應(yīng)用程序的上下文加載和配置是否正確,并驗(yàn)證是否成功將YAML配置文件中的值綁定到相應(yīng)的Java對(duì)象字段上。

運(yùn)行結(jié)果:

三、第二種,松散綁定

使用 @ConfigurationProperties 注解,松散綁定只需要綁定指定節(jié)點(diǎn)的前綴即可,子節(jié)點(diǎn)在 yml 中可以依據(jù)約定, 使用駝峰模式(如:userName)、“—”線(如:允(user-name)、或者全大寫加下劃線(如:USER_NAME) 進(jìn)行綁定即可。

1、還是使用 Student 類

@Component
@Data
@ConfigurationProperties(prefix = "student.info")
public class Student {
    private Integer stuId;
    private String stuName;
    private Integer age;
}

?

這段代碼定義了一個(gè)名為 Student 的 Java 類,使用了 @Component 和 @Data 注解,并且使用了 @ConfigurationProperties 注解對(duì)該類進(jìn)行了配置。

@Component 注解表示這個(gè)類是 Spring 中的一個(gè)組件,會(huì)被 Spring 容器所管理。@Data 注解是 lombok 提供的注解,自動(dòng)生成一些常用方法,如 gettersetter、toString 等等。

@ConfigurationProperties(prefix = "student.info") 注解指定了該類的屬性值從以 student.info 為前綴的配置項(xiàng)中獲取。例如,配置文件中有如下配置:

# 數(shù)據(jù)值綁定
student:
  info:
    stuId: 1001
    stu-name: qiu
    AGE: 18

 則 Student 類中的 stuId 屬性值為 1001,stuName 屬性值為 "qiu",age 屬性值為 18。

這里指定字段的格式我使用了三種,為的是演示可以這樣去寫,在實(shí)際開發(fā)中,大家最好是選擇一種去使用,統(tǒng)一一點(diǎn)。

通過這種方式,我們可以將應(yīng)用程序的配置信息與業(yè)務(wù)邏輯分離,使得配置文件更加清晰易讀,同時(shí)也方便進(jìn)行統(tǒng)一的配置管理。

測(cè)試的結(jié)果和值綁定到一樣,就不測(cè)試了。需要注意的是,實(shí)體類的字段名稱和yml配置的名稱要一樣,不能出現(xiàn)不一致的,不然會(huì)報(bào)錯(cuò)的。

2、綁定實(shí)體

1)新建一個(gè) Card 實(shí)體類

@Data
public class Card {

    private String cardNum;

}

使用 @Data 生成 get、set訪問器就可以了。

2)在 Student 實(shí)體類中引入 Card 實(shí)體類為字段

@Component
@Data
@ConfigurationProperties(prefix = "student.info")
public class Student {
    private Integer stuId;
    private String stuName;
    private Integer age;

    // 實(shí)體
    private Card card;
}

 在原有的 Student 類基礎(chǔ)上,新增了一個(gè)名為 card 的屬性,并且類型為 Card。

yml示例:

# 數(shù)據(jù)值綁定
student:
  info:
    stuId: 1001
    stu-name: qiu
    AGE: 18
    card:
      card-num: 4408812000

 則 Student 類中的 stuId 屬性值為 1001,stuName 屬性值為 "qiu",age 屬性值為 18。Card類中的 cardNum 為 4408812000.

3)測(cè)試

@SpringBootTest
@Slf4j
class Ch03ApplicationTests {

    @Autowired
    private Student student;

    @Test
    void contextLoads() {
        log.info(student.getStuId().toString());
        log.info(student.getStuName());
        log.info(student.getAge().toString());
        log.info(student.getCard().getCardNum());
    }

}

在contextLoads()方法中,使用日志記錄器log輸出了student對(duì)象的一些屬性信息。通過調(diào)用student對(duì)象的get方法獲取學(xué)生的學(xué)號(hào)、姓名、年齡以及身份證號(hào)碼,并通過log.info()方法將它們輸出到日志中。 

運(yùn)行結(jié)果:

 3、綁定數(shù)組

1)在 student 實(shí)體類中新建一個(gè)字段

  // 數(shù)組
    private String[] tels;

yml中綁定 tels 的值:

  # 綁定 array,list,set 集合,多個(gè)值使用逗號(hào)分隔
    tels: # 13223453421,14556766700
      - 13223453421
      - 14556766700

這里呢有兩種寫法,一種是用逗號(hào)隔開,一種是使用 “-”線加空格隔開,不加空格的話,輸出的時(shí)候會(huì)把 “-” 也輸出來。

2)測(cè)試

@SpringBootTest
@Slf4j
class Ch03ApplicationTests {

    @Autowired
    private Student student;

    @Test
    void contextLoads() {
        log.info(student.getStuId().toString());
        log.info(student.getStuName());
        log.info(student.getAge().toString());
        log.info(student.getCard().getCardNum());
        for (String tel : student.getTels()) {
            log.info(tel);
        }
    }

}

綁定了一個(gè)數(shù)組,拿出來只需要循環(huán)就可以啦。

運(yùn)行結(jié)果:

4、綁定 map 

1)在 Student 實(shí)體類中新建一個(gè)字段

 // map
    private Map<String,Integer> score;

 yml 綁定 score 的值:

   # 綁定 map
    score:
      chinese: 85
      english: 60

 因?yàn)?map 是一以鍵值對(duì)保存數(shù)據(jù)的,所以這里的 Chinese 就是鍵,85 就是這個(gè)鍵的值。

 2)測(cè)試

@SpringBootTest
@Slf4j
class Ch03ApplicationTests {

    @Autowired
    private Student student;

    @Test
    void contextLoads() {
        log.info(student.getStuId().toString());
        log.info(student.getStuName());
        log.info(student.getAge().toString());
        log.info(student.getCard().getCardNum());
        for (String tel : student.getTels()) {
            log.info(tel);
        }
        student.getScore().forEach((k,v) -> log.info(k + " : " + v));
      
    }

}

Map的forEach()方法,遍歷了getScore()返回的Map對(duì)象,并通過日志輸出了每個(gè)鍵值對(duì)的內(nèi)容。

運(yùn)行結(jié)果:

5、復(fù)雜的值綁定

1)新建一個(gè) Teacher 實(shí)體類

@Data
public class Teacher {

    private String name;
    private Integer age;

}

2)在 student 實(shí)體類中新加一個(gè)字段

 // 集合里面有個(gè)對(duì)象
    private List<Teacher> teaches;

yml綁定:

    # 綁定復(fù)雜類型(集合中包含對(duì)象)
    teaches:
      - name: Mr.qiu
        age: 21
      - name: Ms.zhi
        age: 22

這是一個(gè) YAML 配置文件,其中 teaches 是一個(gè)復(fù)雜類型,包含了兩個(gè)對(duì)象:Mr.qiu 和 Ms.zhi,它們都擁有 name 和 age 兩個(gè)屬性。

3)測(cè)試

@SpringBootTest
@Slf4j
class Ch03ApplicationTests {

    @Autowired
    private Student student;

    @Test
    void contextLoads() {
        log.info(student.getStuId().toString());
        log.info(student.getStuName());
        log.info(student.getAge().toString());
        log.info(student.getCard().getCardNum());
        for (String tel : student.getTels()) {
            log.info(tel);
        }
        student.getScore().forEach((k,v) -> log.info(k + " : " + v));
        student.getTeaches().forEach( teach -> {
            log.info(teach.getName());
            log.info(teach.getAge().toString());
        });
    }

}

 運(yùn)行結(jié)果:

四、值綁定和松散綁定到優(yōu)點(diǎn)和缺點(diǎn)

YAML 數(shù)據(jù)綁定的值綁定和松散綁定有以下優(yōu)點(diǎn):

  • 簡(jiǎn)單易讀:YAML 格式的數(shù)據(jù)配置文件相對(duì)于傳統(tǒng)的屬性文件更加簡(jiǎn)潔易讀,且支持注釋和多行文本。
  • 靈活性:YAML 的靈活性允許我們?cè)谂渲梦募惺褂脧?fù)雜的數(shù)據(jù)類型,包括數(shù)組、對(duì)象、嵌套對(duì)象等。
  • 易于維護(hù):通過將配置文件中的值綁定到 Java 類上,我們可以使用 Java 對(duì)象的語(yǔ)法來訪問這些值,使得代碼更加易于維護(hù)和閱讀。
  • 配置管理:通過 @ConfigurationProperties 注解,可以將應(yīng)用程序的配置信息與業(yè)務(wù)邏輯分離,使得配置文件更加清晰易讀,同時(shí)也方便進(jìn)行統(tǒng)一的配置管理。

但是,YAML 數(shù)據(jù)綁定的值綁定和松散綁定也有以下缺點(diǎn):

  • 學(xué)習(xí)成本:相比于傳統(tǒng)的屬性文件,使用 YAML 格式的數(shù)據(jù)配置文件需要學(xué)習(xí)新的語(yǔ)法和規(guī)則,需要一些時(shí)間來適應(yīng)。
  • 錯(cuò)誤處理:由于 YAML 的松散綁定特性,當(dāng)配置文件中出現(xiàn)錯(cuò)誤時(shí),可能會(huì)造成不可預(yù)知的結(jié)果,需要開發(fā)者自己注意檢查和處理。
  • 性能問題:相比于傳統(tǒng)的屬性文件,使用 YAML 格式的數(shù)據(jù)配置文件解析和讀取速度可能會(huì)稍慢一些,特別是在處理大量數(shù)據(jù)時(shí)。

綜上所述,在使用 YAML 數(shù)據(jù)綁定時(shí),需要根據(jù)具體情況權(quán)衡其優(yōu)缺點(diǎn),并選擇適合自己的方式來處理配置信息。

到此這篇關(guān)于SpringBoot中yml的數(shù)據(jù)綁定示例的文章就介紹到這了,更多相關(guān)SpringBoot yml數(shù)據(jù)綁定內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論