swagger本身是一個框架,可以用來設計Api,可以提供一個UI界面展示Api文檔,也可以通過UI交互發送數據到服務端進行接口測試。
spring是一個java框架,衆所周知。
而springfox,則將swagger集成到spring中。
springboot集成swagger2的步驟:
1.maven構建的springboot項目,在pom中引入以下兩個依賴來集成swagger:
<!-- 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>
2.在Application.java同級創建Swagger2的配置類Swagger2,代碼示例如下:
package com.mark;
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;
/**
* @author mark
* @date 2019/10/27 11:50
* @description swagger配置類
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.mark"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.description("接口文檔")
.build();
}
}
3.controller方法上添加註解,@ApiOperation
描述接口作用,@ApiImplicitParams
和@ApiImplicitParam
標識接口入參,@ApiResponses
和@ApiResponse
標識接口返回狀態碼,比如200代表成功,-1代表失敗。示例代碼如下:
package com.mark.web.hello;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.*;
/**
* @author mark
* @date 2019/10/24 20:39
*/
@RestController
public class HelloController {
@ApiOperation(value = "Get Hello")
@ApiImplicitParam(name = "name", value = "姓名", defaultValue = "My Friend")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = -1, message = "Fail")
})
@GetMapping("/hello")
public String sayHello(@RequestParam(name = "name", required = false, defaultValue = "My Friend") String name) {
return "Hello " + name;
}
}
4.Model屬性加上註解@ApiModelProperty
標識屬性含義,示例代碼如下:
package com.mark.domain.user;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author guolimin.lc
*/
@Data
public class User {
@ApiModelProperty(value = "主鍵")
private Long id;
@ApiModelProperty(value = "姓名")
private String name;
@ApiModelProperty(value = "年齡")
private Integer age;
}
備註:使用swagger之後,接口返回數據一般就不再定義list或map了,而是基本上都返回model,這樣做是爲了swagger的文檔可以正確顯示接口返回數據。