前言
Swagger
是一套基于 OpenAPI 规范构建的开源工具,可以帮助我们设计、构建、记录以及使用 Rest API。越来越多的公司在项目中使用Swagger
作为文档构建工具,Swagger
主要有一下优点:
- 代码变,文档变。只需要少量的注解,Swagger 就可以根据代码自动生成 API 文档,很好的保证了文档的时效性
- 跨语言性,支持 40 多种语言
- Swagger UI 呈现出来的是一份可交互式的 API 文档,我们可以直接在文档页面尝试 API 的调用,省去了准备复杂的调用参数的过程
- 还可以将文档规范导入相关的工具(例如 SoapUI), 这些工具将会为我们自动地创建自动化测试
如果你还在手写Api
文档,你可以尝试使用swagger
去构建你的文档。你是否已经对 Swagger 产生了浓厚的兴趣了呢?下面我们就将一步一步地在 Spring Boot 项目中集成和使用 Swagger,让我们从准备一个 Spring Boot 的 Web 项目开始吧。
springboot 结合 swagger
1、在pom.xml
中配置依赖
<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、配置swaggerconfig
信息
我们要使用swagger
就需要编写一个swagger
的配置文件,主要用来用来初始化swagger
。配置信息如下:
@EnableSwagger2
@Configuration
//@Profile({"dev","test"})
@ConditionalOnProperty(name = "swagger.enable",havingValue = "true")
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 扫描的包
.apis(RequestHandlerSelectors.basePackage("com.curry.springbootswagger.controller"))
// 选择API路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// swagger ui 的标题
.title("Spring Boot中使用 Swagger2 构建 Restful APIs")
// 描述
.description("更多信息关注公众号 平头哥的技术博文")
// 外链
.termsOfServiceUrl("https://www.jianshu.com/u/008ce054774c")
// 文档的版本信息
.version("1.0")
.build();
}
}
配置类的几个注解说明:
@Configuration
:将该类自动加载到springboot
的上下文中
@EnableSwagger2
:启用swagger
文档此注解也可以加在引导类,如果没有该注解,swagger
文档将不会生效。
@Profile
、@ConditionalOnProperty
两个注解用来做条件判断,在特定的条件下才加载swagger
配置类。一般情况下,在生产环境中我们需要禁用swagger
文档,因为swagger
文档会带来一些安全问题,我们就利用上述两个条件装配注解来解决。下面来说说这两个注解怎么使用?
@Profile({"dev","test"})
:只在开发、测试环境启用swagger
文档。{"dev","test"}
根据你在springboot
中配置的多环境为准。
@ConditionalOnProperty(name = "swagger.enable",havingValue = "true")
:只有在配置文件中添加了swagger.enable=true
的配置环境才启用swagger
文档。
3、编写实体类
@Data
@ApiModel(value = "用户实体类")
public class User implements Serializable {
@ApiModelProperty(value = "业务主键", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
private int id;
@ApiModelProperty(value = "名称", required = true)
private String name;
@ApiModelProperty(value = "手机号码", required = true)
private String mobile;
@ApiModelProperty(value = "电子邮箱", required = true)
private String email;
}
注解说明:
@ApiModel
:用来对类进行描述。主要参数说明:
参数 | 参数说明 |
---|---|
value |
类的名称 |
description |
类的描述 |
@ApiModelProperty
:用来对属性进行描述,主要参数说明
参数 | 参数说明 |
---|---|
value |
字段名称 |
name |
允许覆盖的字段 |
dataType |
参数的数据类型 |
required |
是否必须 |
hidden |
是否不在swagger 中展示 |
accessMode |
数据模式,只读、读写,使用的是AccessMode 枚举类 |
4、编写controller
类
@RestController
@Api(tags = "用户管理", value = "用户管理")
public class UserController {
Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@ApiOperation(value = "查询用户")
@GetMapping(path = "/user")
public ResultDTO findUser() {
ResultDTO resultDTO = new ResultDTO();
try {
resultDTO.setSuccess(true);
resultDTO.setModule(userService.findUser());
} catch (Exception e) {
logger.error(e.getMessage());
resultDTO.setSuccess(false);
resultDTO.setErrorCode("400");
resultDTO.setErrorMsg(e.getMessage());
}
return resultDTO;
}
@ApiOperation(value = "新增用户")
@PostMapping(path = "/user")
public ResultDTO insertUser(@RequestBody User user) {
ResultDTO resultDTO = new ResultDTO();
try {
userService.insertUser(user);
resultDTO.setSuccess(true);
} catch (Exception e) {
resultDTO.setSuccess(false);
resultDTO.setErrorCode("400");
resultDTO.setErrorMsg(e.getMessage());
logger.error(e.getMessage());
}
return resultDTO;
}
@PutMapping(path = "/user")
@ApiOperation(value = "更新用户",notes = "更新用户信息")
public ResultDTO updateUser(@RequestBody User user) {
ResultDTO resultDTO = new ResultDTO();
try {
userService.updateUser(user);
resultDTO.setSuccess(true);
} catch (Exception e) {
resultDTO.setSuccess(false);
resultDTO.setErrorCode("400");
resultDTO.setErrorMsg(e.getMessage());
logger.error(e.getMessage());
}
return resultDTO;
}
@DeleteMapping(path = "/user/{id}")
@ApiOperation(value = "删除用户", notes = "根据ID删除用户信息")
// @ApiImplicitParams({
// @ApiImplicitParam(value="用户id",name = "id",paramType="path")
// })
public ResultDTO deleteUser(@ApiParam(value = "用户id",name = "id") @PathVariable(value = "id") int id) {
ResultDTO resultDTO = new ResultDTO();
try {
userService.deleteUser(id);
resultDTO.setSuccess(true);
} catch (Exception e) {
resultDTO.setSuccess(false);
resultDTO.setErrorCode("400");
resultDTO.setErrorMsg(e.getMessage());
logger.error(e.getMessage());
}
return resultDTO;
}
@DeleteMapping(path = "/user/ingorApi")
@ApiIgnore(value = "我是别忽略的API接口,我将不会在Swagger上显示")
public ResultDTO ignoreApi() {
ResultDTO resultDTO = new ResultDTO();
resultDTO.setSuccess(true);
return resultDTO;
}
}
要是用swagger
来做接口文档,需要在开发接口的时候添加一些接口注释,这样才能生成完整的接口文档。注解说明:
@Api
:作用于类上,用来说明类的作用,
@ApiOperation
:作用在方法上用来对方法进行说明。主要参数:
参数 | 参数说明 |
---|---|
value |
方法的简要说明 |
tags |
方法的主要功能 |
httpMethod |
方法的请求类型,values["GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS","PATCH"] |
@ApiImplicitParams
和@ApiImplicitParam
:用在方法上,对参数进行说明,@ApiImplicitParams
包含多个@ApiImplicitParam
,@ApiImplicitParam
主要参数:
参数 | 参数说明 |
---|---|
name |
字段名称 |
value |
字段描述 |
defaultValue |
字段默认值 |
allowableValues |
允许访问的值 |
required |
是否填 |
dataType |
数据类型 |
paramType |
参数所在的位置[path、query、body、header、form] |
@ApiParam
:作用于单个参数,对于对参数的描述,主要参数说明:
参数 | 参数说明 |
---|---|
name |
字段名称 |
value |
字段描述 |
defaultValue |
字段默认值 |
allowableValues |
允许访问的值 |
required |
是否填 |
dataType |
数据类型 |
@ApiIgnore
:用来忽略该接口,加了@ApiIgnore
的接口将不会在swagger
文档上显示。
5、启动项目
访问http://127.0.0.1:8080/swagger-ui.html
,


如果你觉得这界面不美观,OK,今天平头哥给你介绍一款更符合国人审美的ui
框架swagger-ui-layer
。
结合swagger-ui-layer
要使用swagger-ui-layer
只需要做一个改动,在pom.xml
中做如下调整.
<!--注释掉springfox-swagger-ui-->
<!-- <dependency>-->
<!-- <groupId>io.springfox</groupId>-->
<!-- <artifactId>springfox-swagger-ui</artifactId>-->
<!-- <version>2.9.2</version>-->
<!-- </dependency>-->
<!--添加swagger-ui-layer-->
<dependency>
<groupId>com.github.caspar-chen</groupId>
<artifactId>swagger-ui-layer</artifactId>
<version>1.1.3</version>
</dependency>
重新启动项目,swagger-ui-layer
的访问路径发生了变化,访问http://127.0.0.1:8080/docs.html
,你将看到

更多关于swagger-ui-layer
,点击这里
如果需要在一个swagger
中集成多个项目,请参考程序员DD的博客:Spring Cloud Zuul中使用Swagger汇总API接口文档
demo下载:demo
个人公众号
