Swagger的使用
pom.xml中添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
添加配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.swagger_demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.version("1.0")
.build();
}
}
注解添加文档内容
@Api
:给类添加说明@ApiOperation
:给api方法添加说明@ApiImplicitParam
: 给api方法参数添加说明。@ApiImplicitParams
:包含多个 @ApiImplicitParam@ApiResponses
:用于表示一组响应@ApiModel
:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)@ApiResponse
:组装返回参数说明@ApiResponses
:包含多个 @ApiResponse
案列:
@Controller
@Api(value = "测试类控制器")
public class IndexController {
@RequestMapping(value = "/index",method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "测试方法1")
public String index() {
return "hi,how are you?";
}
@RequestMapping(value = "/index2",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "测试方法2")
@ApiImplicitParams(value = {
@ApiImplicitParam(paramType = "query",name = "id",value = "用户ID",dataType = "int",required = true),
@ApiImplicitParam(paramType = "query",name = "name",value = "用户名",dataType = "String",required = true)
})
@ApiResponses({
@ApiResponse(code = 404,message = "请求参数缺少!")
})
public String index2(Integer id,String name) {
return "hi,your post params id="+id+",name="+name;
}
}
http://localhost:8081/swagger-ui.html
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191008175415624.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQxNDM5MTM=,size_16,color_FFFFFF,t_70)