Spring Boot整合Swagger
前言
為了完成專案自帶文件的需求,花了一定的時間研究
Spring Boot
整合Swagger
。看了官方文件和一些部落格,差不多搭出一個比較通用的架子。文末會分享出案例專案。
基本概述
本文使用
Spring Boot
+Spring Fox
的方式整合Swagger
框架。
案例
引入依賴
<properties>
<swagger.version>2.7.0</swagger.version>
</properties>
<dependencies>
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- swagger2 ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
</dependencies>
Swagger配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.switchvov.swagger"))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
/**
* 配置認證模式
*/
private List<ApiKey> securitySchemes() {
return newArrayList(new ApiKey("Authorization", "Authorization", "header"));
}
/**
* 配置認證上下文
*/
private List<SecurityContext> securityContexts() {
return newArrayList(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.any())
.build());
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(new SecurityReference("Authorization", authorizationScopes));
}
/**
* 專案資訊
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger測試專案 RESTful APIs")
.version("1.0")
.build();
}
}
配置方式
基本概述
Swagger官方Wiki 註解
swagger2常用註解說明
swagger註釋API詳細說明PS:以上幾篇文章已經將
Swagger
註解的使用方式及作用闡述的非常清楚了。這裡只給出程式碼案例。PS:
springfox-swagger2:2.7.0
已經支援泛型返回物件。
注意:千萬不要在@ApiOperation
註解裡限定response()
,讓框架推斷型別就行了。
控制器
@RestController
@RequestMapping(value = "/user", produces = "application/json")
@Api(value = "User", tags = {"User"}, description = "使用者相關")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
@ApiOperation(value = "使用ID查詢使用者")
@ApiImplicitParams({
@ApiImplicitParam(value = "ID", name = "id", dataType = "int", paramType = "path", required = true, defaultValue = "1")
})
@ApiResponses({
@ApiResponse(code = 400, message = "請求引數有誤"),
@ApiResponse(code = 401, message = "未授權"),
@ApiResponse(code = 403, message = "禁止訪問"),
@ApiResponse(code = 404, message = "請求路徑不存在"),
@ApiResponse(code = 500, message = "伺服器內部錯誤")
})
public ResponseResult<User> getById(@PathVariable("id") Integer id) {
User user = userService.getById(id);
return ResponseResult.successWithData(user);
}
@PostMapping("")
@ApiOperation(value = "建立使用者")
@ApiResponses({
@ApiResponse(code = 400, message = "請求引數有誤"),
@ApiResponse(code = 401, message = "未授權"),
@ApiResponse(code = 403, message = "禁止訪問"),
@ApiResponse(code = 404, message = "請求路徑不存在"),
@ApiResponse(code = 500, message = "伺服器內部錯誤")
})
public ResponseResult<User> createUser(@Validated @RequestBody User user) {
User dbUser = userService.createUser(user);
return ResponseResult.successWithData(dbUser);
}
}
統一響應類
@ApiModel(description = "響應物件")
public class ResponseResult<T> {
private static final int SUCCESS_CODE = 0;
private static final String SUCCESS_MESSAGE = "成功";
@ApiModelProperty(value = "響應碼", name = "code", required = true, example = "" + SUCCESS_CODE)
private int code;
@ApiModelProperty(value = "響應訊息", name = "msg", required = true, example = SUCCESS_MESSAGE)
private String msg;
@ApiModelProperty(value = "響應資料", name = "data")
private T data;
// 省略get、set方法等等,詳見原始碼
}
使用者Model
PS:使用者model使用了
lombok
、jpa
、validator
,只需要關注@Api
開頭的註解就行了。
@Data
@Entity(name = "users")
@ApiModel(description = "使用者Model")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Null(message = "id必須為空")
@ApiModelProperty(value = "使用者ID", name = "id")
private Integer id;
@Column
@NotBlank(message = "使用者名稱不能為空")
@ApiModelProperty(value = "使用者名稱", name = "username", required = true, example = "zhaoliu")
private String username;
@Column
@NotBlank(message = "密碼不能為空")
@ApiModelProperty(value = "密碼", name = "password", required = true, example = "123456")
private String password;
}
文件介面
原始碼
GitHub:swagger-demo
參考資訊
- SpringFox官網
- Swagger官方Wiki 註解
- Spring Boot中使用Swagger2構建強大的RESTful API文件
- 第四章 springboot + swagger
- Spring啟動RESTful API文件使用Swagger 2
- swagger2常用註解說明
- swagger註釋API詳細說明
- Swagger2 新增HTTP head引數
- Swagger2 非全域性、無需重複輸入的Head引數(Token)配置
分享並記錄所學所見