SpringBoot 2.X Kotlin與Swagger2

image

這里有個地方需要注意,在測試WebFlux集成Swagger2的時(shí)候存在問題,看了官方文檔現(xiàn)在2.9.2還沒有集成,所以引入的jar是spring-boot-starter-web,而不是spring-boot-starter-webflux

本章目的

在項(xiàng)目中集成文檔及接口測試平臺,使用Swagger2可以快速幫助我們編寫最新的API接口文檔,再也不用擔(dān)心開會前仍忙于整理各種資料了,間接提升了團(tuán)隊(duì)開發(fā)的溝通效率。

添加Swagger2依賴

在<code>pom.xml</code>中加入Swagger2的依賴

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

創(chuàng)建Swagger2配置

package io.intodream.kotlin04.config

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.spi.DocumentationType
import springfox.documentation.spring.web.plugins.Docket
import springfox.documentation.swagger2.annotations.EnableSwagger2

/**
 * @description
 * 構(gòu)建一個Swagger2配置文件
 * @author Jwenk
 * @copyright intoDream.io 筑夢科技
 * @email xmsjgzs@163.com
 * @date 2019-03-31,21:55
 */
@Configuration
@EnableSwagger2
class Swagger2Config {

    @Bean
    fun createRestApi(): Docket {
        return Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
    }

    private fun apiInfo(): ApiInfo {
        return ApiInfoBuilder()
                .title("Spring Boot2.X Kotlin 中使用Swagger2構(gòu)建RESTFul APIs")
                .description("更多SpringBoot2.X Kotlin 文章請關(guān)注:惜魚博客")
                .termsOfServiceUrl("https://www.intodream.io")
                .contact(Contact("惜魚", "https://www.tisnz.com", "xmsjgzs@163.com"))
                .version("1.0.0")
                .build()
    }
}

如上代碼所示,通過<code>@Configuration</code>注解,讓Spring來加載該類配置。再通過<code>@EnableSwagger2</code>注解來啟用Swagger2。

再通過createRestApi函數(shù)創(chuàng)建Docket的Bean之后,apiInfo()用來創(chuàng)建該Api的基本信息(這些基本信息會展現(xiàn)在文檔頁面中)。select()函數(shù)返回一個ApiSelectorBuilder實(shí)例用來控制哪些接口暴露給Swagger來展現(xiàn),本例采用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,并產(chǎn)生文檔內(nèi)容(除了被@ApiIgnore指定的請求)。

編寫文檔內(nèi)容

在完成上面的配置后,其實(shí)Swagger會自動幫我們生成API的文檔,但是自動生成的文檔顯示并不友好,我們通常需要添加一些額外的信息,這時(shí)候就需要通過@ApiOperation注解在API上增加說明,通過@ApiImplicitParams@ApiImplicitParam注解來給參數(shù)增加說明。

package io.intodream.kotlin04.web

import io.intodream.kotlin04.model.Student
import io.swagger.annotations.Api
import io.swagger.annotations.ApiImplicitParam
import io.swagger.annotations.ApiOperation
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap

/**
 * @description
 *
 * @author Jwenk
 * @copyright intoDream.io 筑夢科技
 * @email xmsjgzs@163.com
 * @date 2019-03-31,22:07
 */
@Api(value = "學(xué)生信息相關(guān)接口", tags = ["學(xué)生"])
@RestController
@RequestMapping("/api/student")
class StudentController {

    private var repository : ConcurrentMap<String, Student> = ConcurrentHashMap<String, Student>()
    private val logger : Logger = LoggerFactory.getLogger(this.javaClass)

    @ApiOperation(value = "保存一條學(xué)生信息")
    @ApiImplicitParam(name = "student", value = "學(xué)生詳細(xì)實(shí)體student", required = true, dataType = "Student")
    @PostMapping("/")
    fun save(@RequestBody student: Student): Student? {
        logger.info("請求參數(shù):{}", student)
        return repository.put(student.id, student)
    }

    @ApiOperation(value = "獲取學(xué)生列表")
    @GetMapping("/list")
    fun listStudent():List<Student> {
        val studentList = ArrayList<Student>(repository.values)
        logger.info("返回?cái)?shù)據(jù):{}", studentList)
        return studentList
    }

    @ApiOperation(value = "通過學(xué)生編號獲取學(xué)生詳細(xì)信息")
    @ApiImplicitParam(name = "studentId", value = "學(xué)生編號", required = true, dataType = "String")
    @GetMapping("/info")
    fun studentInfo(@RequestParam studentId: String): Student? {
        val student : Student? = repository.get(studentId)
        logger.info("studentId:{}, 對應(yīng)的數(shù)據(jù):{}", student)
        return student
    }

    @ApiImplicitParam(name = "studentId", value = "學(xué)生編號", required = true, dataType = "String")
    @ApiOperation(value = "刪除學(xué)生信息")
    @DeleteMapping("/")
    fun deleteStudent(@RequestParam studentId: String): String {
        logger.info("刪除學(xué)生編號:{}", studentId)
        repository.remove(studentId)
        return "success"
    }
}

完成上述代碼添加上,啟動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html。就能看到前文所展示的RESTful API的頁面。我們可以再點(diǎn)開具體的API請求,以POST類型的/api/student/請求為例,可找到上述代碼中我們配置的Notes信息以及參數(shù)student的描述信息,如下圖所示。

image

image

image

API文檔訪問與調(diào)試

在上圖請求的頁面中,我們看到student的Example Value是個輸入框?是的,Swagger除了查看接口功能外,還提供了調(diào)試測試功能,我們可以點(diǎn)擊上圖中右側(cè)的Model Schema(黃色區(qū)域:它指明了User的數(shù)據(jù)結(jié)構(gòu)),此時(shí)Example Value中就有了student對象的模板,我們只需要稍適修改,點(diǎn)擊下方“Try it out!”按鈕,即可完成了一次請求調(diào)用!

到此我們集成Swagger2就完成了,大家可以多測試一下看返回結(jié)果是否正確,感覺是不是寫接口文檔方便了很多呢。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容