在服务端的开发过程中,后端开发人员往往会提供很多API接口出来供客户端的开发人员使用,经常会维护一份文档,注明每个接口的访问方式,需要的参数和返回的结果等基本信息。这种传统的API书写方式很费时间,而且容易造成因为接口文档更新不及时导致前后端开发人员的沟通成本的增加。利用swagger可以很方便、直观的将后台所定义接口展示给客户端开发人员,而且还给后台开发人员节省了很多时间成本。swagger这么方便好用,那我们现在就开始进行整合吧
1、引入swagger所需要的jar包
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.9</version> </dependency>
2、自定义swagger的基本配置
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot Demo中使用Swagger2构建RESTful APIs") .version("1.0.0") .build(); } }
3、编写测试的controller
@RestController public class ProductCategoryController { @Autowired private ProductCategoryService categoryService; @GetMapping("db/findByCategoryType/{type}") @ApiOperation(value = "查询类型", notes = "根据CategoryType来查询类型") public ResultVO getCategory(@PathVariable("type") Integer type) { return ResultVOUtil.success(categoryService.findByCategoryType(type)); } }
4、在 GitHub 上下载 SwaggerUI 项目(https://github.com/swagger-api/swagger-ui),将dist下所有内容拷贝到本地项目resource/static/swagger下面, 并修改 index.html
//url: "http://petstore.swagger.io/v2/swagger.json", //url: "http://localhost:8086/demo/v2/api-docs", url: location.protocol + '//' + location.host + "/demo/v2/api-docs",
5、然后访问http://localhost:8086/demo/swagger/index.html