乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      jackson學(xué)習(xí)之九:springboot整合(配置文件)

       新進(jìn)小設(shè)計(jì) 2021-05-05

      歡迎訪問(wèn)我的GitHub

      這里分類(lèi)和匯總了欣宸的全部原創(chuàng)(含配套源碼):https://github.com/zq2599/blog_demos

      系列文章匯總

      關(guān)于springboot整合jackson

      • 本文是《jackson學(xué)習(xí)》系列的第九篇,學(xué)習(xí)如何在springboot項(xiàng)目中使用jackson,以springboot-2.3.3版本為例,jackson是springboot的默認(rèn)json處理工具,如下圖紅框所示,jackson在maven配置中被spring-boot-starter-web間接依賴,可直接使用:

      在這里插入圖片描述

      • 在springboot項(xiàng)目中常用的配置方式有兩種:
      1. 用properties或yml配置文件來(lái)配置,即本篇的內(nèi)容;
      2. 用配置類(lèi)來(lái)配置,這是下一篇文章的主題;

      本篇概覽

      今天實(shí)戰(zhàn)內(nèi)容如下:

      1. 開(kāi)發(fā)springboot應(yīng)用,體驗(yàn)springboot默認(rèn)支持jackson,包括jackson注解和ObjectMapper實(shí)例的注入;
      2. application.yml中添加jackson配置,驗(yàn)證是否生效;

      源碼下載

      1. 如果您不想編碼,可以在GitHub下載所有源碼,地址和鏈接信息如下表所示(https://github.com/zq2599/blog_demos):
      名稱(chēng) 鏈接 備注
      項(xiàng)目主頁(yè) https://github.com/zq2599/blog_demos 該項(xiàng)目在GitHub上的主頁(yè)
      git倉(cāng)庫(kù)地址(https) https://github.com/zq2599/blog_demos.git 該項(xiàng)目源碼的倉(cāng)庫(kù)地址,https協(xié)議
      git倉(cāng)庫(kù)地址(ssh) git@github.com:zq2599/blog_demos.git 該項(xiàng)目源碼的倉(cāng)庫(kù)地址,ssh協(xié)議
      1. 這個(gè)git項(xiàng)目中有多個(gè)文件夾,本章的應(yīng)用在jacksondemo文件夾下,如下圖紅框所示:

      在這里插入圖片描述

      1. jacksondemo是父子結(jié)構(gòu)的工程,本篇的代碼在springbootproperties子工程中,如下圖:

      在這里插入圖片描述

      開(kāi)始實(shí)戰(zhàn)

      1. 由于同屬于《jackson學(xué)習(xí)》系列文章,因此本篇的springboot工程作為jacksondemo的子工程存在,pom.xml如下,需要注意的是parent不能使用spring-boot-starter-parent,而是通過(guò)dependencyManagement節(jié)點(diǎn)來(lái)引入springboot依賴:
      <?xml version="1.0" encoding="UTF-8"?>
      <project xmlns="http://maven./POM/4.0.0" xmlns:xsi="http://www./2001/XMLSchema-instance"
               xsi:schemaLocation="http://maven./POM/4.0.0 https://maven./xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>
          <parent>
              <artifactId>jacksondemo</artifactId>
              <groupId>com.bolingcavalry</groupId>
              <version>1.0-SNAPSHOT</version>
              <relativePath>../pom.xml</relativePath>
          </parent>
          <groupId>com.bolingcavalry</groupId>
          <artifactId>springbootproperties</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <name>springbootproperties</name>
          <description>Demo project for Spring Boot</description>
      
          <properties>
              <java.version>1.8</java.version>
          </properties>
      
      
          <!--不用spring-boot-starter-parent作為parent時(shí)的配置-->
          <dependencyManagement>
              <dependencies>
                  <dependency>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-dependencies</artifactId>
                      <version>2.3.3.RELEASE</version>
                      <type>pom</type>
                      <scope>import</scope>
                  </dependency>
              </dependencies>
          </dependencyManagement>
      
          <dependencies>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
      
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
                  <exclusions>
                      <exclusion>
                          <groupId>org.junit.vintage</groupId>
                          <artifactId>junit-vintage-engine</artifactId>
                      </exclusion>
                  </exclusions>
              </dependency>
      
              <!-- swagger依賴 -->
              <dependency>
                  <groupId>io.springfox</groupId>
                  <artifactId>springfox-swagger2</artifactId>
              </dependency>
              <!-- swagger-ui -->
              <dependency>
                  <groupId>io.springfox</groupId>
                  <artifactId>springfox-swagger-ui</artifactId>
              </dependency>
          </dependencies>
      
          <build>
              <plugins>
                  <plugin>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-maven-plugin</artifactId>
                  </plugin>
              </plugins>
          </build>
      
      </project>
      
      1. 啟動(dòng)類(lèi)很平常:
      package com.bolingcavalry.springbootproperties;
      
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      
      @SpringBootApplication
      public class SpringbootpropertiesApplication {
      
          public static void main(String[] args) {
              SpringApplication.run(SpringbootpropertiesApplication.class, args);
          }
      }
      
      1. 由于用到了swagger,因此要添加swagger配置:
      package com.bolingcavalry.springbootproperties;
      
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import springfox.documentation.builders.ApiInfoBuilder;
      import springfox.documentation.builders.PathSelectors;
      import springfox.documentation.builders.RequestHandlerSelectors;
      import springfox.documentation.service.ApiInfo;
      import springfox.documentation.service.Contact;
      import springfox.documentation.service.Tag;
      import springfox.documentation.spi.DocumentationType;
      import springfox.documentation.spring.web.plugins.Docket;
      import springfox.documentation.swagger2.annotations.EnableSwagger2;
      
      @Configuration
      @EnableSwagger2
      public class SwaggerConfig {
      
          @Bean
          public Docket createRestApi() {
              return new Docket(DocumentationType.SWAGGER_2)
                      .apiInfo(apiInfo())
                      .tags(new Tag("JsonPropertySerializationController", "JsonProperty相關(guān)測(cè)試"))
                      .select()
                      // 當(dāng)前包路徑
                      .apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.springbootproperties.controller"))
                      .paths(PathSelectors.any())
                      .build();
          }
      
          //構(gòu)建 api文檔的詳細(xì)信息函數(shù),注意這里的注解引用的是哪個(gè)
          private ApiInfo apiInfo() {
              return new ApiInfoBuilder()
                      //頁(yè)面標(biāo)題
                      .title("SpringBoot整合Jackson(基于配置文件)")
                      //創(chuàng)建人
                      .contact(new Contact("程序員欣宸", "https://github.com/zq2599/blog_demos", "zq2599@gmail.com"))
                      //版本號(hào)
                      .version("1.0")
                      //描述
                      .description("API 描述")
                      .build();
          }
      }
      
      1. 序列化和反序列化用到的Bean類(lèi),可見(jiàn)使用了JsonProperty屬性來(lái)設(shè)置序列化和反序列化時(shí)的json屬性名,field0字段刻意沒(méi)有g(shù)et方法,是為了驗(yàn)證JsonProperty的序列化能力:
      package com.bolingcavalry.springbootproperties.bean;
      
      import com.fasterxml.jackson.annotation.JsonProperty;
      import io.swagger.annotations.ApiModel;
      import io.swagger.annotations.ApiModelProperty;
      
      import java.util.Date;
      
      @ApiModel(description = "JsonProperty注解測(cè)試類(lèi)")
      public class Test {
      
          @ApiModelProperty(value = "私有成員變量")
          @JsonProperty(value = "json_field0", index = 1)
          private Date field0 = new Date();
      
          public void setField0(Date field0) {
              this.field0 = field0;
          }
      
          @ApiModelProperty(value = "來(lái)自get方法的字符串")
          @JsonProperty(value = "json_field1", index = 0)
          public String getField1() {
              return "111";
          }
      
          @Override
          public String toString() {
              return "Test{" +
                      "field0=" + field0 +
                      '}';
          }
      }
      
      1. 測(cè)試用的Controller代碼如下,很簡(jiǎn)單只有兩個(gè)接口,serialization返回序列化結(jié)果,deserialization接受客戶端請(qǐng)求參數(shù),反序列化成實(shí)例,通過(guò)toString()來(lái)檢查反序列化的結(jié)果,另外,還通過(guò)Autowired注解從spring容器中將ObjectMapper實(shí)例直接拿來(lái)用:
      package com.bolingcavalry.springbootproperties.controller;
      
      import com.bolingcavalry.springbootproperties.bean.Test;
      import com.fasterxml.jackson.core.JsonProcessingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
      import io.swagger.annotations.Api;
      import io.swagger.annotations.ApiOperation;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.web.bind.annotation.RequestBody;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestMethod;
      import org.springframework.web.bind.annotation.RestController;
      
      @RestController
      @RequestMapping("/jsonproperty")
      @Api(tags = {"JsonPropertySerializationController"})
      public class JsonPropertySerializationController {
      
          private static final Logger logger = LoggerFactory.getLogger(JsonPropertySerializationController.class);
      
          @Autowired
          ObjectMapper mapper;
      
          @ApiOperation(value = "測(cè)試序列化", notes = "測(cè)試序列化")
          @RequestMapping(value = "/serialization", method = RequestMethod.GET)
          public Test serialization() throws JsonProcessingException {
      
              Test test = new Test();
              logger.info(mapper.writeValueAsString(test));
      
              return test;
          }
      
          @ApiOperation(value = "測(cè)試反序列化", notes="測(cè)試反序列化")
          @RequestMapping(value = "/deserialization",method = RequestMethod.PUT)
          public String deserialization(@RequestBody Test test) {
              return test.toString();
          }
      }
      

      驗(yàn)證(不用配置文件)

      1. 先來(lái)看看沒(méi)有配置文件時(shí),默認(rèn)的jackson配置的表現(xiàn),直接在IDEA上運(yùn)行SpringbootpropertiesApplication;
      2. 瀏覽器訪問(wèn)http://localhost:8080/swagger-ui.html ,如下圖紅框1,json_field0和json_field1都是JsonProperty注釋?zhuān)霈F(xiàn)在了swagger的model中,這證明jackson注解已經(jīng)生效:

      在這里插入圖片描述

      1. 點(diǎn)擊上圖的紅框2,看看springboot引用返回的序列化結(jié)果,如下圖:

      在這里插入圖片描述

      1. 另外,上述紅框中的json格式,每個(gè)屬性單獨(dú)一行,像是做了格式化調(diào)整的,這是springboot做的?還是swagger展示的時(shí)候做的?用瀏覽器訪問(wèn)http://localhost:8080/jsonproperty/serialization ,結(jié)果如下,可見(jiàn)springboot返回的是未經(jīng)過(guò)格式化的json

      在這里插入圖片描述

      • 接下來(lái)咱們添加jackson相關(guān)的配置信息并驗(yàn)證是否生效;

      添加配置文件并驗(yàn)證

      1. resources目錄新增application.yml文件,內(nèi)容如下:
      spring:
        jackson:
          # 日期格式化
          date-format: yyyy-MM-dd HH:mm:ss
          # 序列化相關(guān)
          serialization:
            # 格式化輸出
            indent_output: true
            # 忽略無(wú)法轉(zhuǎn)換的對(duì)象
            fail_on_empty_beans: true
          # 反序列化相關(guān)
          deserialization:
            # 解析json時(shí),遇到不存在的屬性就忽略
            fail_on_unknown_properties: false
          # 設(shè)置空如何序列化
          defaultPropertyInclusion: NON_EMPTY
          parser:
            # 允許特殊和轉(zhuǎn)義符
            allow_unquoted_control_chars: true
            # 允許單引號(hào)
            allow_single_quotes: true
      
      1. 將鼠標(biāo)放置下圖紅框位置,再按住Ctlr鍵,IDEA會(huì)彈出一個(gè)浮層,提示該配置對(duì)應(yīng)的jackson代碼,如下圖:

      在這里插入圖片描述

      1. 在上圖中,按住Ctlr鍵,用鼠標(biāo)點(diǎn)擊紅框位置即可打開(kāi)此配置對(duì)應(yīng)的jackson源碼,如下圖:

      在這里插入圖片描述
      4. 重新運(yùn)行springboot應(yīng)用,用瀏覽器訪問(wèn):http://localhost:8080/jsonproperty/serialization ,結(jié)果如下圖,可見(jiàn)json_field0的格式變成了yyyy-MM-dd HH:mm:ss,而且json輸出也做了格式化,證明application.yml中的配置已經(jīng)生效:

      在這里插入圖片描述
      5. 再來(lái)試試反序列化,打開(kāi)swagger頁(yè)面,操作和響應(yīng)如下圖所示,注意紅框1里面請(qǐng)求參數(shù)的格式:

      在這里插入圖片描述

      • 至此,在springboot中通過(guò)yml配置jackson的操作實(shí)戰(zhàn)就完成了,接下來(lái)的章節(jié),咱們?cè)谂渲妙?lèi)中用代碼來(lái)完成yml的配置;

      你不孤單,欣宸原創(chuàng)一路相伴

      1. Java系列
      2. Spring系列
      3. Docker系列
      4. kubernetes系列
      5. 數(shù)據(jù)庫(kù)+中間件系列
      6. DevOps系列

      歡迎關(guān)注公眾號(hào):程序員欣宸

      微信搜索「程序員欣宸」,我是欣宸,期待與您一同暢游Java世界...
      https://github.com/zq2599/blog_demos

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類(lèi)似文章 更多