《深入理解Spring Cloud与微服务构建》学习笔记(七)~SpringBoot 整合 Swagger2,搭建在线api文档
一、在项目 pom.xml 引入 swagger 依赖 springfox-swagger2 和 springfox-swagger-ui 如:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
二、配置Swagger2
新建一个配置类,添加@Configuration注解 ,表明是一个配置类,添加@EnableSwagger2注解,开启Swagger2功能。还需要注入一个Docket的Bean,该Bean包含了apiInfo,基本api文档的描述信息,以及包扫描的基本包名信息如:
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.snail.test.spring_boot_demo1024"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("构建Swagger2在线文档")
.description("使用Spring Boot 构建")
.termsOfServiceUrl("http://localhost:8080")
.version("1.0")
.build();
}
}
三、写生成文档注解
Swagger2通过注解生成api文档,常用的一些注解如下:
@Api: 修饰整个类,用于描述Controller
@ApiOperation :描述类的方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:”用对象来接收参数。
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse: HTTP 响应的一个描述。
@ApiResponses: HTTP 响应的整体描述。
@Apilgnore: 使用该注解,表示 Swagger2 忽略这个 API
@ApiError: 发生错误返回的信息。
@ApiParamlmplicit: 一个请求参数
@ApiParamsimplicit: 多个请求参数。
四、Web层
新建一个Controller,新建一个方法,构建一个以资源为中心的 RESTful 风格的 API 接口。
方法需要通过 @ApiOperation 注解描述当前api的具体说明,value为接口名字,notes为该接口详细描述说明。
如果不需要生成则加入 @Apilgnore 注解即可。代码如下:
@RequestMapping("/user")
@RestController
public class UserController {
@ApiOperation(value = "用户列表" , notes = "用户列表notes")
@RequestMapping(value="",method = RequestMethod.GET)
public List<String> getUser(){
List<String> list = new ArrayList();
return list ;
}
}
启动项目,访问:http://localhost:8080/swagger-ui.html 可以看到一个简单的在线文档构建完成:
demo代码:https://download.****.net/download/ssdate/10741152