對於開發人員來講,在開發過程當中得自測是不可避省得,像postman這種工具就對模擬http請求提供了便捷。還有就是接口文檔也是使人頭疼得事情,Swagger就很好得解決了這種事情。html
Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset. Find out how Swagger can help you design and document your APIs at scale.
藉助Swagger開源和專業工具集,爲用戶,團隊和企業簡化API開發。瞭解Swagger如何幫助您大規模設計和記錄API。
由於Swagger官方的API文檔界面很差看,因此就找到了swagger-bootstrap-ui,界面好看還能夠自定義請求參數文檔。 後來又找到了該團隊開發的springboot版本,在原有的基礎上加強,Get it !
官網文檔地址:https://doc.xiaominfo.com/kni...java
<!-- Swagger --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.8</version> </dependency>
3.x版本引用的是springfox3和OpenAPI3規範,目前是不穩定版本,因此選擇引用2.x的版本~~~~git
新建SwaggerConfig.javagithub
@Configuration @EnableSwagger2WebMvc public class SwaggerConfig { @Bean(value = "api") public Docket defaultApi2() { Docket docket=new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() .description("# 文檔的描述") .version("1.0") .build()) //分組名稱 .groupName("1.X版本") .select() //這裏指定Controller掃描包路徑 .apis(RequestHandlerSelectors.basePackage("com.ify.sampleAdmin.web.controller")) .paths(PathSelectors.any()) .build(); return docket; } }
接口添加swagger註解web
@RestController @RequestMapping("/user") @Api(tags = "用戶模塊") public class UserController extends BaseController { @GetMapping("/user") @ApiOperation(value = "獲取根據ID獲取用戶") @ApiImplicitParam(name = "id",value = "用戶id",required = true) public ResResult getUser(@RequestParam(value = "id") String id) { return ResResult.success(); } }
運行http://localhost:8181/sa/doc.html
spring
@ApiImplicitParam
註解用在GET請求上是好用的,可是若是POST接口參數是對象時,會把沒必要要的參數都顯示出來,例如bootstrap
@PostMapping("/user") @ApiOperation(value = "獲取根據ID獲取用戶") @ApiImplicitParam(name = "id",value = "用戶id",required = true) public ResResult getUser(User user) { return ResResult.success(); }
這是個POST接口,聲明瞭只有一個id參數時必須傳遞的,參數是用User實體接收。結構swagger文檔所有顯示出來api
固然Knife4j
提供了過濾和包含參數的註解,能夠排除或包含必須參數來簡潔文檔。springboot
@ApiOperationSupport(ignoreParameters = {"id","orderDate.id"})
@ApiOperationSupport(order = 40,includeParameters = {"ignoreLabels","longUser.ids"})
可是,大多數人在開發接口的時候使用的傳遞參數都是Map
或者JSONObject
這類參數,Knife4j
就提供了動態請求參數添加文檔註釋
例如:app
@PostMapping("/user") @ApiOperation(value = "post用戶") @DynamicParameters(properties = { @DynamicParameter(name = "id",value = "ID",example = "X000111",required = true,dataTypeClass = String.class), @DynamicParameter(name = "username",value = "用戶名",required = true), @DynamicParameter(name = "password",value = "密碼",required = true), @DynamicParameter(name = "sex",value = "性別",required = false), }) public ResResult getUser(@RequestBody JSONObject params) { return ResResult.success(); }
swagger顯示了必要的參數,並能夠標明哪些參數是必傳的! 真是個不錯的功能。
Knife4j
是對swagger-bootstrap-ui的升級,而swagger-bootstrap-ui是隻是對官方界面的美化。Knife4j
版本則包含了給官方swagger的功能並加以加強,我的認爲很好用。