先赞后看,养成好习惯
引言
Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful Web服务。Swagger 3,也称为OpenAPI 3.0,是目前Swagger的最新版本,它提供了更丰富的API描述和更强大的工具集。在SpringBoot项目中整合Swagger 3可以帮助开发者快速生成API文档,提高开发效率。
目录
准备工作
首先在IDEA中创建一个SpringBoot项目
选择一个Spring Web依赖
添加swagger的依赖
添加一个springfox-boot-starter就可以了
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
swagger配置类
新建软件包config,在config中新建SwaggerConfig配置类
package com.star.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* swagger配置类
*
* @author WYH
* @since 2024/5/6 下午2:11
*/
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.star.controller")) // 替换为您的Controller所在的包路径
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("后端接口文档") // 文档标题
.description("前后端交互接口") // 文档路径
.version("1.0.0") // 文档版本
.build();
}
}
注解使用
Swagger UI 是一个强大的工具,它可以根据你的代码中的注解自动生成 API 文档。以下是一些常用的 Swagger 注解及其用法:
1. @Api
用于类上,描述 Controller 的作用。
- value:描述类的作用。
- tags:说明该类的作用,非空时将覆盖 `value` 的值。
@Api(value = "用户管理", tags = "用户管理相关接口")
public class UserController {
// ...
}
2. @ApiOperation
用于方法,描述类中的一个方法或者接口。
- value:对方法的描述。
@ApiOperation(value = "获取用户列表")
@GetMapping("/users")
public List<User> listUsers() {
// ...
}
3. @ApiParam
用于参数,单个参数描述。
- name:参数名。
- value:参数描述。
- required:参数是否必须。
@GetMapping("/users/{id}")
public User getUserById(
@ApiParam(name = "id", value = "用户ID", required = true) @PathVariable Long id) {
// ...
}
4. @ApiModel
用于类,表示对类进行说明,通常用于参数接收。
@ApiModel(description = "用户实体")
public class User {
// ...
}
5. @ApiProperty
用于字段,描述对象的一个字段。
public class User {
@ApiProperty(name = "姓名", value = "用户的真实姓名")
private String name;
// ...
}
6. @ApiImplicitParam
用于方法,描述一个请求参数。
@ApiOperation(value = "创建用户")
@PostMapping("/users")
public User createUser(
@ApiImplicitParam(name = "name", value = "用户姓名", required = true) @RequestParam String name) {
// ...
}
7. @ApiImplicitParams
用于方法,包含多个 @ApiImplicitParam。
@PostMapping("/users")
@ApiOperation(value = "创建用户")
public User createUser(
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "用户姓名", required = true),
@ApiImplicitParam(name = "age", value = "用户年龄", required = false)
}) @RequestBody User user) {
// ...
}
8. @ApiResponse
用于方法,描述单个出参信息。
@ApiResponse(code = 200, message = "操作成功")
@ApiResponse(code = 400, message = "请求参数有误")
9. @ApiResponses
用于方法,包含多个 @ApiResponse。
@ApiResponses({
@ApiResponse(code = 200, message = "操作成功"),
@ApiResponse(code = 400, message = "请求参数有误"),
@ApiResponse(code = 500, message = "内部错误")
})
10. @ApiIgnore
用于类或方法,忽略当前的 API。
@ApiIgnore
public class IgnoredController {
// ...
}
11. @ApiError
用于方法,接口错误所返回的信息。
@ApiOperation(value = "操作接口")
@GetMapping("/error")
@ApiResponses({
@ApiResponse(code = 400, message = "请求参数有误"),
@ApiError(code = 500, message = "服务器异常")
})
public ResponseEntity<?> error() {
// ...
}
12. @EnableSwagger2
用于配置类,启用 Swagger2。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
// ...
}
13. Docket
配置 Swagger。
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
这些注解可以组合使用,以生成详细且用户友好的 API 文档。Swagger UI 支持多种语言,包括 Java、Scala、Kotlin、Groovy、TypeScript、Ruby、Python 和 Go 等。
接口文档地址
假设后端端口为8080
http://localhost:8080/swagger-ui/index.html
可能遇到的报错解决
空指针:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2024-05-06 18:39:48.200 ERROR 15096 --- [ main] o.s.boot.SpringApplication : Application run failedorg.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2024-05-06 18:39:48.200 ERROR 15096 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
如果你遇到像我一样的空指针异常,可以在application.yml或application.properties中加一条配置
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
注意格式
如果该教程对你有用的话,不妨点个赞,点个关注再走吧!
接Java毕设、课设,SpringBoot、Vue,Python,提供代码远程调试指导,有需要可以+V了解