目录
1. 项目环境
- IDEA 2020.1.4
- Maven 3.6
- JDK 1.8
- SpringBoot 2.x
- Swagger 2.9.2
项目文件在GitHub(欢迎star⭐):
https://github.com/Gang-bb/Gangbb-SpringBoot
如有疑问或是建议,欢迎评论区留言或者QQ:949526365
2. 开始整合
2.1 引入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.2 配置SwaggerConfig
package com.gangbb.gangbbspringbootswagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author : Gangbb
* @ClassName : SwaggerConfig
* @Description :
* @Date : 2021/1/24 9:47
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//访问http://localhost:8080/swagger-ui.html可以看到API文档
@Bean
public Docket api(Environment environment) {
//设置要显示的Swagger环境
Profiles profiles = Profiles.of("dev", "test");
//获取项目环境:是生产环境还是发布环境
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2) // 指定api类型为swagger2
.apiInfo(apiInfo()) // 用于定义api文档汇总信息
.enable(flag)//是否启用swagger,如果为false则swagger不能再浏览器中访问
.select() //通过select()方法配置扫描接口,RequestHandlerSelectors配置如何扫描接口
.apis(RequestHandlerSelectors.any()) // 指定扫描的controller包
.paths(PathSelectors.any()) //通过paths()方法配置扫描接口,PathSelectors配置如何扫描接口
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Gangbb Swagger API")
.description("Gangbb 的 Swagger UI")
.contact(new Contact("Gangbb", "http://xxx.xxx.com/联系人访问链接", "949526365@qq.com"))
.version("1.0.0")
.termsOfServiceUrl("") // 网站地址
.build();
}
}
Swagger实例Bean是Docket,所以通过配置Docket实例来配置Swaggger。
其中.apis()中
RequestHandlerSelectors.any():扫描所有,项目中的所有接口都会被扫描到
RequestHandlerSelectors.none():不扫描接口
RequestHandlerSelectors除了设置any外还可以配置basePackage方式扫描接口
例如:.apis(RequestHandlerSelectors.basePackage(“com.gangbb.gangbbspringbootswagger.controller”))
只扫描controller包中接口
RequestHandlerSelectors.withMethodAnnotation(GetMapping.class)只扫描get请求
RequestHandlerSelectors.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口
其中.path()中
- PathSelectors.any() 任何请求都扫描
- PathSelectors.none() 任何请求都不扫描
- PathSelectors.regex() 通过正则表达式控制,返回true扫描,false不扫描
- PathSelectors.ant() 通过ant()表达式控制,返回true扫描,false不扫描
以上配置后可以使用Swagger。访问地址:
http://localhost:8080/swagger-ui.html

2.3 配置多个API分组
在实际开发中可能有多个api分组比如V1版本V2版本,或者是分为需要身份校验的API和通用common不需要身份校验的API(比如登录和注册)。
只需要配置多个docket
2.4 定义实体类
package com.gangbb.gangbbspringbootswagger.bean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @author : Gangbb
* @ClassName : City
* @Description :
* @Date : 2021/1/24 10:08
*/
@ApiModel(value = "City", description = "城市实体类")
public class City {
@ApiModelProperty("城市id")
private Long id;
@ApiModelProperty("城市名")
private String name;
@ApiModelProperty("城市描述")
private String description;
public City(Long id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
@Override
public String toString() {
return "City{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@ApiModel:用于JavaBean上面,表示对JavaBean 的功能描述
@ApiModel的用途有2个:
- 当请求数据描述,即
@RequestBody时, 用于封装请求(包括数据的各种校验)数据; - 当响应值是对象时,即
@ResponseBody时,用于返回值对象的描述。
@ApiModelProperty:用在JavaBean类的属性上面,说明属性的含义
3. Controller中实践
package com.gangbb.gangbbspringbootswagger.controller;
import com.gangbb.gangbbspringbootswagger.bean.City;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author : Gangbb
* @ClassName : CityController
* @Description :
* @Date : 2021/1/24 10:02
*/
@RestController
@Api(value = "CityController")
@RequestMapping("city")
public class CityController {
@ApiOperation("通过id获取city信息")
@GetMapping("/{id}")
public City getCityById(@PathVariable(value = "id") Long id) {
City city = new City(id, "LA", "a city from US");
return city;
}
@ApiOperation("获取city列表信息")
@GetMapping("/list")
public List<City> getCityList() {
List<City> list = new ArrayList<>();
City city1 = new City(1L, "LA", "a city from US");
City city2 = new City(2L, "南宁", "a city from China");
list.add(city1);
list.add(city2);
return list;
}
@ApiOperation(value = "新增城市", notes = "根据城市实体创建城市")
@PostMapping
public @ResponseBody
Map<String, Object> addCity(@RequestBody City city) {
Map<String, Object> map = new HashMap<>();
map.put("result", "success");
return map;
}
@PostMapping("/multi")
@ApiOperation(value = "添加多个city")
public List<City> multi(@RequestBody List<City> cities) {
return cities;
}
@PostMapping("/{id}/file")
@ApiOperation(value = "文件上传")
public String file(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
return file.getOriginalFilename();
}
@ApiOperation(value = "更新用户", notes = "根据用户id更新用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "城市id", required = true, dataType = "Long", paramType = "path", example = "1"),
@ApiImplicitParam(name = "city", value = "城市实体", required = true, dataType = "City") })
@PutMapping("/{id}")
public @ResponseBody Map<String, Object> updateCity(@PathVariable(value = "id") Long id, @RequestBody City city) {
Map<String, Object> map = new HashMap<>();
map.put("result", "success");
return map;
}
@DeleteMapping("/{id}")
@ApiOperation(value = "删除city", notes = "删除city")
public void delete(@PathVariable Integer id) {
}
}

4. 常用注解整合
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数
每个注解具体解释,再Idea中直接按Ctrl+注解,可以直接看注解有哪些参数和每个参数大概意思。
或者以下博客介绍:
https://blog.youkuaiyun.com/qq_37460214/article/details/105304952
5. 后话
本文只介绍了整合Swagger最基础的使用。
后续可以加入
- 添加全局Authorization参数
- 配置OAuth2.0
- 配置Swagger的账号密码
相关内容官方介绍文档:
https://swagger.io/docs/specification/authentication/bearer-authentication/

258

被折叠的 条评论
为什么被折叠?



