《深入理解Spring Cloud與微服務構建》學習筆記(七)~SpringBoot 整合 Swagger2,搭建線上api文件
阿新 • • 發佈:2018-12-17
一、在專案 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 ;
}
}