优雅的自动生成接口文档(推荐3种方法)
1.集成swagger,使用注解生成,自动生成接口文档
2.集成apiDoc,在源代码中通过创建API注释从而自动生成api说明文档
3.集成knife4f,knife4j是为Java MVC框架集成Swagger生成Api文档的工具
今天我们使用swagger2,进行接口文档自动生成,come on:
1.pom.xml文件添加:
io.springfoxspringfox-swagger22.2.2io.springfoxspringfox-swagger-ui2.2.2
2.Swagger2配置类
@Configuration@EnableSwagger2public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.wookong.web")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2自动生成接口文档") .description("Spring Boot系列教程文章请关注:古稀程序猿") .termsOfServiceUrl("http://www.baidu.com/") .contact("古稀") .version("1.0") .build(); }}
3.通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明。
@ApiOperation(value="创建person") @ApiImplicitParam(name = "person", value = "用户详细实体person") @RequestMapping(value="", method=RequestMethod.POST) public String postPerson(@RequestBody Person p) { return""; }
@ApiOperation(value="更新person信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID"), @ApiImplicitParam(name = "person", value = "用户详细实体person") }) @RequestMapping(value="/{id}", method=RequestMethod.Post) public String putPerson(@PathVariable Long id, @RequestBody Person p) { …… return "success"; }
4.访问http://localhost:8080/swagger-ui.html
![c0bbfdc3188182bec10dbfcc2dded011.png](https://img-blog.csdnimg.cn/img_convert/c0bbfdc3188182bec10dbfcc2dded011.png)
以上三个都不难,主要是你要知道,有哪些插件可以干这些事,用起来都挺简单的,我个人建议使用注释ApiDoc,无侵入式编程,我们的代码就不会显得很杂乱,同时培养我们规范注释的书写。
好了,今天我们Swagger2就介绍到这,如有疑问,欢迎留言讨论。