jackson學習之十(終篇):springboot整合(配置類)

w39發表於2021-09-09

歡迎訪問我的GitHub

https://github.com/zq2599/blog_demos

內容:所有原創文章分類彙總及配套原始碼,涉及Java、Docker、Kubernetes、DevOPS等;

系列文章彙總

本篇概覽

  • 本文是《jackson學習》系列的終篇,經過前面的一系列實戰,相信您已可以熟練使用jackson靈活的執行各種json序列化和反序列化操作,那麼,本篇就以輕鬆的方式來完成整個系列吧;
  • 上一篇介紹的是在springboot中通過配置檔案對jackson做設定,今天要聊的是另一種常用的jackson配置方式:配置類,就是自己編寫程式碼例項化和配置springboot全域性使用的ObjectMapper例項;

原始碼下載

  1. 如果您不想編碼,可以在GitHub下載所有原始碼,地址和連結資訊如下表所示(https://github.com/zq2599/blog_demos):
名稱 連結 備註
專案主頁 https://github.com/zq2599/blog_demos 該專案在GitHub上的主頁
git倉庫地址(https) https://github.com/zq2599/blog_demos.git 該專案原始碼的倉庫地址,https協議
git倉庫地址(ssh) git@github.com:zq2599/blog_demos.git 該專案原始碼的倉庫地址,ssh協議
  1. 這個git專案中有多個資料夾,本章的應用在jacksondemo資料夾下,如下圖紅框所示:

在這裡插入圖片描述

  1. jacksondemo是父子結構的工程,本篇的程式碼在springbootconfigbean子工程中,如下圖:

在這裡插入圖片描述

編碼

  1. 在父工程jacksondemo下新增子工程springbootconfigbean,pom.xml如下:
<?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>
        <artifactId>jacksondemo</artifactId>
        <groupId>com.bolingcavalry</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.bolingcavalry</groupId>
    <artifactId>springbootconfigbean</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootconfigbean</name>
    <description>Demo project for Spring Boot with Jackson, configuration from config bean</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <!--不用spring-boot-starter-parent作為parent時的配置-->
    <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. 本文最重要的程式碼是配置類JacksonConfig.java,如下,需要ConditionalOnMissingBean註解避免衝突,另外還給例項指定了名稱customizeObjectMapper,如果應用中通過Autowired使用此例項,需要指定這個名字,避免報錯"There is more than one bean of 'ObjectMapper ' type":
@Configuration
public class JacksonConfig {

    @Bean("customizeObjectMapper")
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper mapper = builder.build();

        // 日期格式
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));

        // 美化輸出
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        return mapper;
    }
}
  1. 對於JacksonConfig.getObjectMapper方法內的設定,如果您想做更多設定,請參考《jackson學習之三:常用API操作》裡面的設定內容;
  • 啟動類依然很簡單:
package com.bolingcavalry.springbootconfigbean;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootConfigBeanApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootConfigBeanApplication.class, args);
    }

}
  1. swagger配置:
package com.bolingcavalry.springbootconfigbean;

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相關測試"))
                .select()
                // 當前包路徑
                .apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.springbootconfigbean.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    //構建 api文件的詳細資訊函式,注意這裡的註解引用的是哪個
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //頁面標題
                .title("SpringBoot整合Jackson(基於配置檔案)")
                //建立人
                .contact(new Contact("程式設計師欣宸", "https://github.com/zq2599/blog_demos", "zq2599@gmail.com"))
                //版本號
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}
  1. 最後是測試用的Controller類,要注意的是在使用ObjectMapper例項的地方,用Autowired註解的時候,記得帶上Qualifier註解
package com.bolingcavalry.springbootconfigbean.controller;

import com.bolingcavalry.springbootconfigbean.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.beans.factory.annotation.Qualifier;
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);

    @Qualifier("customizeObjectMapper")
    @Autowired
    ObjectMapper mapper;

    @ApiOperation(value = "測試序列化", notes = "測試序列化")
    @RequestMapping(value = "/serialization", method = RequestMethod.GET)
    public Test serialization() throws JsonProcessingException {

        Test test = new Test();
        logger.info(mapper.writeValueAsString(test));

        return test;
    }

    @ApiOperation(value = "測試反序列化", notes="測試反序列化")
    @RequestMapping(value = "/deserialization",method = RequestMethod.PUT)
    public String deserialization(@RequestBody Test test) {
        return test.toString();
    }
}

驗證

  1. 啟動SpringbootConfigBeanApplication後,瀏覽器開啟:http://localhost:8080/swagger-ui.html
  2. 先驗證序列化介面/jsonproperty/serialization:

在這裡插入圖片描述
3. 再驗證反序列化介面 /jsonproperty/deserialization:

在這裡插入圖片描述

  • 至此,整個《jackson學習》系列就全部完成了,希望這十篇內容能夠給您帶來一些參考,助您在編碼過程中更加得心應手的使用Jackson;

你不孤單,欣宸原創一路相伴

  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 資料庫+中介軟體系列
  6. DevOps系列

歡迎關注公眾號:程式設計師欣宸

微信搜尋「程式設計師欣宸」,我是欣宸,期待與您一同暢遊Java世界...
https://github.com/zq2599/blog_demos

相關文章