一.SpringBoot使用Swagger2构建API文档:
第一步:在pom.xml中加入Swagger2的依赖:
<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>
第二步:创建Swagger2配置类:
package com.offcn.springbootdemo.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 { //1 声明api 文档的属性 构建器 private ApiInfo apiInfo(){ return new ApiInfoBuilder().title("springboot中使用在线文档构建RestFul风格 Apis") .description("在线文档").termsOfServiceUrl("http://aaa.com/").contact("java") .version("1.0").build(); } // 2 配置核心配置信息 public Docket creatRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select().apis(RequestHandlerSelectors.basePackage("com.aaa.springbootdemo.controller")) .paths(PathSelectors.any()).build(); } }
第三步:在controller层的代码中添加文档注释:
通过@ApiOperation注解来给API增加说明
通过@ApiImplicitParams和@ApiImplicitParam注解来给参数增加说明
查看Swagger2文档的访问地址:http://localhost:8080/swagger-ui.html