這里有個地方需要注意稿蹲,在測試WebFlux集成Swagger2的時候存在問題扭勉,看了官方文檔現(xiàn)在2.9.2還沒有集成,所以引入的jar是
spring-boot-starter-web
,而不是spring-boot-starter-webflux
本章目的
在項目中集成文檔及接口測試平臺苛聘,使用Swagger2可以快速幫助我們編寫最新的API接口文檔涂炎,再也不用擔(dān)心開會前仍忙于整理各種資料了,間接提升了團隊開發(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
實例用來控制哪些接口暴露給Swagger來展現(xiàn)蛀序,本例采用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller
定義的API活烙,并產(chǎn)生文檔內(nèi)容(除了被@ApiIgnore
指定的請求)徐裸。
編寫文檔內(nèi)容
在完成上面的配置后,其實Swagger會自動幫我們生成API的文檔啸盏,但是自動生成的文檔顯示并不友好重贺,我們通常需要添加一些額外的信息,這時候就需要通過@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é)生詳細實體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("返回數(shù)據(jù):{}", studentList)
return studentList
}
@ApiOperation(value = "通過學(xué)生編號獲取學(xué)生詳細信息")
@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的頁面舟茶。我們可以再點開具體的API請求谭期,以POST類型的/api/student/請求為例堵第,可找到上述代碼中我們配置的Notes信息以及參數(shù)student的描述信息,如下圖所示隧出。
API文檔訪問與調(diào)試
在上圖請求的頁面中踏志,我們看到student的Example Value是個輸入框?是的鸳劳,Swagger除了查看接口功能外狰贯,還提供了調(diào)試測試功能,我們可以點擊上圖中右側(cè)的Model Schema(黃色區(qū)域:它指明了User的數(shù)據(jù)結(jié)構(gòu))赏廓,此時Example Value中就有了student對象的模板涵紊,我們只需要稍適修改,點擊下方“Try it out幔摸!”按鈕摸柄,即可完成了一次請求調(diào)用!
到此我們集成Swagger2就完成了既忆,大家可以多測試一下看返回結(jié)果是否正確驱负,感覺是不是寫接口文檔方便了很多呢。