一、swagger是什么
Swagger 是一个用于生成、描述和调用 RESTful 接口的 Web 服务。必须使用派生注解请求(GetMapping、PostMapping、PutMapping、DeleteMapping)。
通俗的来讲,Swagger 就是将项目中所有(想要暴露的)接口(接口就是该方法的请求路径,不是interface)展现在页面上,并且可以进行接口调用和测试的服务,(调接口就是给后端发送对应的请求)
1、是一款让你更好的书写API文档的规范且完整框架。
2、提供描述、生产、消费和可视化RESTful Web Service。
3、是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面
访问路径:有两个可以进行测试
http://127.0.0.1:8080/swagger-ui.html#/
http://localhost:8080/doc.html
二、springboot集成swagger2
1、导入依赖
<!--springboot集成swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--访问路径http://127.0.0.1:8110/swagger-ui.html#/,可以设置请求头-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--访问路径http://127.0.0.1:8110/doc.html,可以设置请求头-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.2</version>
</dependency>
2、配置类
@Configuration//标为为配置类,相当于spring.xml
@EnableSwagger2
public class SwagerrConfiguration {
private static ApiInfo DEFAULT = null;
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2);
}
}
3、解决 高版本SpringBoot整合Swagger 启动报错Failed to start bean ‘documentationPluginsBootstrapper‘ 问题
在yaml文件中:
spring:
#解决 高版本SpringBoot整合Swagger 启动报错Failed to start bean ‘documentationPluginsBootstrapper‘ 问题
mvc:
pathmatch:
matching-strategy: ant_path_matcher
4、测试
@RestController
@RequestMapping("/test")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user") //使用 @GetMapping这个派生注解,就是为了测试swagger
//测试swagger访问这个路径http://localhost:8080/swagger-ui.html
public List<User> test(Integer pageNum,Integer pageSize){
PageInfo<User> pageInfo = userService.selectAllName(pageNum, pageSize);
List<User> list = pageInfo.getList();
System.out.println("pageInfo:"+pageInfo);
return list;
}
@PostMapping("/testPost")
public String testPost(User user){
return user.getName();
}
@RequestMapping("view")
public String view(){
return "哈哈哈哈哈哈哈哈哈哈哈哈哈";
}
}
4、访问swagger
访问路径:
http://127.0.0.1:8080/doc.html
或者
http://127.0.0.1:8080/swagger-ui.html#/
必须使用 @GetMapping("/user") 使用 @GetMapping这个派生注解请求(GetMapping、PostMapping、PutMapping、DeleteMapping),就是为了测试swagger
点击try it out
输入实体类对应的属性:
点击execute
下面便是响应的数据:
三、swagger2常用的注解
Swagger2 是一个用于生成和展示 API 文档的工具,它提供了一组注解来描述和配置 API 接口。
@Api | 用于对整个 API 的描述,可以用在类上。 |
@ApiOperation | 对单个接口的描述,包括接口的作用、请求方法、URL 等信息,可以用在方法上。 |
@ApiParam | 对单个参数的描述,包括参数的名称、类型、是否必须等信息,可以用在方法的参数上。 |
@ApiModel | 对请求或响应的数据模型进行描述,可以用在实体类上。 |
@ApiModelProperty | 对实体类中的属性进行描述,包括属性的名称、类型、示例值等信息,可以用在实体类的属性上。 |
@ApiIgnore | 忽略某个接口,不在 API 文档中显示该接口。 |
@ApiImplicitParam | 用于描述请求参数,比如请求头、请求体等,可以用在方法上。 |
@ApiImplicitParams | 用于描述多个请求参数,可以用在方法上。 |
@ApiResponse | 对响应进行描述,包括响应的状态码、说明等信息,可以用在方法上。 |
@ApiResponses | 用于描述多个响应,可以用在方法上。 |
@ApiError | 对错误响应进行描述,可以用在方法上 |
这些注解可以根据具体的需求和场景进行灵活组合和使用,以生成清晰、准确的 API 文档。