本文将介绍RESTful API的重磅好伙伴Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API。具体效果如下图所示:
添加Swagger2依赖
添加Swagger2依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
创建Swagger2配置类
package com.eastw.swagger.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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* description : Swagger2配置类
* Created by WangD.
* Date 2018/7/23
* version : 1.0.0
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.eastw.swagger.controller")) 你项目的controller
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() { 界面初识信息
return new ApiInfoBuilder()
.title("SwaggerApi")
.description("show description")
.termsOfServiceUrl("http://blog.didispace.com/")
.contact("eastw")
.version("1.0")
.build();
}
}
编写controller
@RestController
@Api( value = "swagger测试" ,description = "swagger测试接口")
public class SwaggerApi {
@PostMapping("/test1")
@ApiOperation( value = "test-username",notes = "param-username")
//@ApiImplicitParam(name = "username" ,value = "用户名", required = true,dataType = "String")
public String test1(@RequestParam("username") String username){
return username;
}