Swagger
什么是Swagger?
- OpenAPI规范(OpenAPI Specification 简称OAS)是Linux基金会的一个项目,试图通过定义一种用来描述API格式或API定义的语言,来规范RESTful服务开发过程,并且已经发布并开源在GitHub上:https://github.com/OAI/OpenAPI-Specification
- Swagger是全球最大的OpenAPI规范(OAS)API开发工具框架,Swagger是一个在线接口文档的生成工具,前后端开发人员依据接口文档进行开发,只要添加Swagger的依赖和配置信息即可使用它
1.引入依赖
1 2 3 4 5 6
| <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.9.0.RELEASE</version> </dependency>
|
2.添加配置
1 2 3 4 5 6 7
| swagger: title: "学成在线内容管理系统" description: "内容系统管理系统对课程相关信息进行管理" base-package: com.xuecheng.content enabled: true version: 1.0.0
|
3.在启动类上添加注解
1 2 3 4 5 6 7
| @SpringBootApplication @EnableSwagger2Doc public class ContentApplication { public static void main(String[] args) { SpringApplication.run(ContentApplication.class, args); } }
|
4.访问swagger文档
1
| http://localhost:63040/content/swagger-ui.html
|
63040是服务端口号,/content是在配置文件中配置了server.servlet.context-path
访问路径后加/swagger-ui.html即可访问

5.优化swagger文档信息
1 2 3 4 5 6 7 8 9 10
| @Api(value = "课程信息管理接口", tags = "课程信息管理接口") @RestController public class CourseBaseInfoController {
@ApiOperation("课程查询接口") @PostMapping("/course/list") public PageResult<CourseBase> list(PageParams pageParams,@RequestBody(required = false) QueryCourseParamsDto queryCourseParamsDto) { return null; } }
|
1 2 3 4 5 6 7 8 9 10 11 12
| @Data @ToString @NoArgsConstructor @AllArgsConstructor public class PageParams { @ApiModelProperty(value = "页码") private Long pageNo = 1L; @ApiModelProperty(value = "每页记录数") private Long pageSize = 10L; }
|
| @Api |
修饰整个类,描述Controller的作用 |
| @ApiOperation |
描述一个类的一个方法,或者说一个接口 |
| @ApiParam |
单个参数描述 |
| @ApiModel |
用对象来接收参数 |
| @ApiModelProperty |
用对象接收参数时,描述对象的一个字段 |
| @ApiResponse |
HTTP响应其中1个描述 |
| @ApiResponses |
HTTP响应整体描述 |
| @ApiIgnore |
使用该注解忽略这个API |
| @ApiError |
发生错误返回的信息 |
| @ApiImplicitParam |
一个请求参数 |
| @ApiImplicitParams |
多个请求参数 |

6.可以通过”Try it out”来测试接口