怎樣給Swagger換皮膚?
上文我們講到在Spring Boot中集成Swagger2的組件,那今天我們就來聊聊怎樣給Swagger換個皮膚呢?環境搭建:使用Spring Boot依賴swagger-spring-boot-starter進行快速構建。具體swagger-spring-boot-starter可以參考:https://github.com/SpringForA... 。構建工具是Maven,開發工具是IDEA,JDK版本是1.8。
第一步:Maven快速構建Spring Boot的web項目
第二步:解壓,IDEA導入項目
第三步:集成swagger-spring-boot-starter
pom中依賴:
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
添加@EnableSwagger2Doc添加允許啓用swagger註解,默認情況下就能產生所有當前Spring MVC加載的請求映射文檔。
第四步:配置swagger
# 在application.properties進行配置
swagger.title=碼歌學院API
swagger.description=碼歌學院相關接口API文檔
swagger.version=1.1
swagger.base-package=com.mage
其他具體配置請參考GitHub,https://github.com/SpringForA...。注意在IDEA中配置文件存在中文,那麼需要將其配置文件的編碼設置成utf-8。具體設置:File -> Settings -> Editor -> File Encodings將Properties Files (*.properties)下的Default encoding for properties files設置爲UTF-8,將Transparent native-to-ascii conversion前的勾選上。
第五步:編寫TestController
package com.mage.swagger02.controller;
import com.mage.swagger02.model.Test;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("test")
@Api(tags = "測試API接口")
public class TestController {
@GetMapping("")
@ApiOperation(value="獲取列表數據", notes="獲取列表下測試數據")
public String list() {
return "查詢列表數據!";
}
@GetMapping("{id}")
@ApiOperation(value="獲取ID數據", notes="根據ID獲取某條測試數據")
@ApiImplicitParam(name = "id", value = "主鍵id", paramType = "path", required = true)
public String find(@PathVariable Integer id) {
return String.format("根據主鍵查詢數據: %d", id);
}
@PostMapping("")
@ApiOperation(value="新增數據")
@ApiParam(name = "test", value = "添加的測試模型實體")
public String add(@RequestBody Test test) {
return "插入數據!";
}
@PutMapping("{id}")
@ApiOperation(value="更新數據", notes="根據ID更新測試數據")
@ApiImplicitParam(name = "id", value = "主鍵id", paramType = "path", required = true)
public String update(@PathVariable Integer id, @ApiParam(name = "test", value = "更新的測試模型實體") @RequestBody Test test) {
return String.format("根據主鍵更新一條記錄: %d", id);
}
@DeleteMapping("{id}")
@ApiOperation(value="刪除數據", notes="根據ID刪除測試數據")
@ApiImplicitParam(name = "id", value = "主鍵id", paramType = "path", required = true)
public String delete(@PathVariable Integer id) {
return String.format("根據主鍵刪除記錄: %d", id);
}
}
第六步:啓動執行,瀏覽器輸入http://localhost:8080/swagger-ui.html
第七步:換皮膚
大家如果覺得swagger這種皮膚不好看,那麼可以更換,只需要在pom中引入一下jar包:
<dependency>
<groupId>com.github.caspar-chen</groupId>
<artifactId>swagger-ui-layer</artifactId>
<version>1.1.2</version>
</dependency>
然後瀏覽器輸入:http://localhost:8080/docs.html
好了換膚完成,源碼下載:https://github.com/magekang/s...