1、Swagger2介绍
Swagger2这套自动化文档工具来生成文档,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。
2、SpringBoot开启Swagger2支持
1、导入依赖
<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>
2、设置配置类
package com.offcn.demo.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; @Configuration @EnableSwagger2 public class SwaggerConfig { public ApiInfo apiInfo(){ return new ApiInfoBuilder().title("Spring Boot中使用Swagger2构建RESTful APIs").description("u就业") .termsOfServiceUrl("http://www.ujiuye.com/").contact("Sunny").version("0.0.1").build(); } @Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.offcn.demo.Controller")) .paths(PathSelectors.any()).build(); } }
3、在controller层中的代码添加文档注释
通过@ApiOperation注解来给API增加说明 通过@ApiImplicitParams@ApiImplicitParam注解来给参数增加说明
@GetMapping("/getMap") @ApiOperation(value = "获得数据",notes = "获得数据") @ApiImplicitParam(name = "id" ,value = "用户id",required = true,dataType = "Integer")//required是否是必填属性 public Map getMap(Integer id){ Map<String,String> map=new HashMap<>(); map.put("name","xzy"); return map;
}
@RequestMapping("/test/{id}")
@ApiOperation(value = "输出汽车的id和name",notes = "输出汽车的id和name")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "汽车id",dataType = "Integer",required = true),
@ApiImplicitParam(name = "name",value = "汽车牌子",dataType = "String",required = true)
})
public Car getCar(@PathVariable("id") Integer id, @RequestParam("name") String name){
Car c = new Car(id, name, 100000, new Date());
return c;
}
4、查看生成的文档
http://localhost:8080/swagger-ui.html