天天看點

Swagger2的使用

Swagger2 可以動态生成Api接口文檔,并且提供測試接口,降低溝通成本,促進項目高效開發。

一、swagger2的相關依賴

<!--swagger-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
           

二、建立Swagger2配置類

@Configuration注解,讓Spring來加載該類配置。

@EnableSwagger2注解來啟用Swagger2。

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
        		//apiInfo()用來建立該Api的基本資訊(這些基本資訊會展現在文檔頁面中)
                .apiInfo(apiInfo())
                //select()函數傳回一個ApiSelectorBuilder執行個體用來控制哪些接口暴露給Swagger來展現
                .select()
                //該包下的controller類生成api文檔(除了被@ApiIgnore指定的請求)
                .apis(RequestHandlerSelectors.basePackage("com.funnee.security"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Restful API")
                .description("Funnee's swagger")
                .termsOfServiceUrl("http://localhost:8080")
                .version("1.0")
                .build();
    }
}
           

三、swagger2的通路位址

swagger2的預設通路位址為:URL(目前項目)/swagger-ui.html

swagger2的通路位址和頁面也可自定義:

  • 把swagger的項目目錄拷貝到本地項目;
  • 新增配置檔案,添加配置項

    springfox.documentation.swagger.v2.path = swagger本地項目的路徑

  • 自定義頁面

四、swagger2的文檔說明相關注解

@Api 用于類上,說明該類的作用。可以标記一個Controller類做為swagger 文檔資源

示例:

@Api(value = "xxx", description = "xxx")

@ApiOperation 用于方法上,說明方法的作用,每一個url資源的定義

示例:

@ApiOperation(value = "xxx",httpMethod="POST", notes= "xxx",response=String.class)

@ApiParam 用于方法、參數、字段上,請求屬性

示例:

public List<User> addUser(@RequestBody @ApiParam(value = "user object", required = true) User user)

@ApiImplicitParams 用于方法上,包含一組參數說明

@ApiImplicitParam 用于方法上,用在@ApiImplicitParams注解中,指定一個請求參數的各個方面

@ApiResponse 用于方法上,響應配置

示例:

@ApiResponse(code = 400, message = "Invalid user supplied")

@ApiResponses 用于方法上,響應配置集合

示例:

@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })

@ApiIgnore 用于類,屬性,方法上,忽略某項api,使用@ApiIgnore

示例代碼:

@RestController
@RequestMapping("/user")
@Api(value = "使用者查詢接口", description = "使用者查詢接口")
public class UserController {

    @GetMapping
    @JsonView(User.UserSimpleView.class)
    @ApiOperation(value = "根據條件查詢使用者資訊",notes = "查詢使用者資訊")
    @ApiImplicitParams({@ApiImplicitParam(name = "page",value = "每頁大小"),@ApiImplicitParam(name="name",value = "使用者姓名")})
    public List<User> query(UserQueryCondition userQueryCondition, @PageableDefault(page = 2,size = 10,sort = {"name,asc","age,desc"}) Pageable pageable){
    //...
    }
}
           

在swagger2中的效果圖:

Swagger2的使用

五、swagger代碼生成器

Swagger Codegen是一個開源的代碼生成器,根據Swagger定義的RESTful API可以自動生成建立服務端和用戶端的連接配接的api代碼。

GitHub: https://github.com/swagger-api/swagger-codegen