swagger官方文档:API Documentation & Design Tools for Teams | Swagger
(不管学习啥,读官方文档总没错)
什么是swagger
- 号称世界上最流行的Api框架;
- RestFul Api 文档在线自动生成工具,Api文档与API定义同步更新,实现边编写边实时更新,方便多人在线合作开发
- 直接运行,可以在线测试API接口
- 支持多种语言: (Java,Php....
现在我们基于springboot项目集成Swagger:
新建一个springboot项目,基于maven,首先导入万能web依赖
然后实现我们helloworld的controller接口,因为我们没有编写前端页面,就用RestController返回字符串进行环境测试。
package com.chenxi.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello world";
}
}
成功访问,基本web环境没有问题,接下来引入swagger。
使用swagger所需依赖:(注意!使用最新3.0.0版本可能会访问swagger-ui.html报错!建议降版本至2.9.2)
- swagger2
- swagger-ui
<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.9.3版本,一定要在springboot配置文件中添加:
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
启动后访问http://localhost:8080/swagger-ui.html
访问成功!
接下来配置我们的swagger
- Swagger的bean实例Docket;
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
我们点进Docket源码可以看到:
而DocumentationType中有三个属性可以选:
我们使用的是2.9.2版本。顾选择SWAGGER_2
- 而我们还得创建一个返回ApiInfo的Bean实例,这部分是配置我们Swagger页面中Swagger信息部分的,并且翻遍源码,该类并未编写set方法,只可通过构造器注入值。
@Bean
public ApiInfo apiInfo(){
Contact contact = new Contact("chenxi", "https://i.csdn.net/#/user-center/profile?spm=1000.2115.3001.5111", "785822438@qq.com");
return new ApiInfo(
"晨曦 Swagger Restful API",
"代码和人一个能跑就行",
"1.0",
"https://luischen.com/",
contact,
"Swagger官网",
"https://swagger.io/",
new ArrayList()
);
}
这样基本的配置就完成啦!Swagger的使用体验还是要在具体项目中才能体验到哦!