【接口篇】SpringBoot 整合 Swagger3 实现在线 API 文档

写在最前

Swagger 不了解,或者想整合 Swagger2 的童鞋请点击:【接口篇】SpringBoot 整合 Swagger2 实现在线 API 文档

SpringBoot 整合 Swagger3

1.引入 Swagger3 依赖

<!-- 引入Swagger3依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
复制代码

2.编写 Swagger3 配置文件

/**
 * Swagger配置类
 *
 * @author Strive
 */
@Configuration
@EnableOpenApi
public class Swagger3Config {
  @Bean
  public Docket docket() {
    return new Docket(DocumentationType.OAS_30)
        .apiInfo(apiInfo())
        .enable(true)
        .select()
        // apis: 添加swagger接口提取范围
        .apis(RequestHandlerSelectors.basePackage("com.csp.mingyue.swagger3.controller"))
        // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
        .paths(PathSelectors.any())
        .build();
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("Swagger3 测试接口文档")
        .description("【接口篇】SpringBoot 整合 Swagger3 实现在线 API 文档")
        .contact(
            new Contact(
                "Strive", "https://gitee.com/csps/mingyue-springboot-learning", "[email protected]"))
        .version("3.0")
        .build();
  }
}
复制代码

3.编写接口

其余代码参考码云 Demo:mingyue-springboot-swagger3

/** @author Strive */
@Api(tags = "用户模块")
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class MingYueUserController {

  private final MingYueUserService mingYueUserService;

  @ApiOperation("根据用户ID查询用户信息")
  @GetMapping("/{userId}")
  public ResponseEntity<MingYueUser> queryUserById(@PathVariable Long userId) {
    return ResponseEntity.ok(mingYueUserService.queryUserById(userId));
  }

  @ApiOperation("添加用户")
  @PostMapping
  public ResponseEntity<Long> addUser(@RequestBody MingYueUser user) {
    return ResponseEntity.ok(mingYueUserService.addUser(user));
  }

  @ApiOperation("更新用户")
  @PutMapping
  public ResponseEntity<String> updateUser(@RequestBody MingYueUser user) {
    return ResponseEntity.ok(mingYueUserService.updateUser(user));
  }

  @ApiOperation("根据用户ID删除用户")
  @DeleteMapping("/{userId}")
  public ResponseEntity<String> deleteUser(@PathVariable Long userId) {
    return ResponseEntity.ok(mingYueUserService.deleteUser(userId));
  }
}
复制代码

4.启动项目

访问:http://localhost:8080/swagger-ui/index.html

image-20220415155831690

补充说明

Spring Boot 2.6.6 启动报错

报错如下:

Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
复制代码

解决方法,在 application.yml 增加如下配置:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
复制代码

猜你喜欢

转载自juejin.im/post/7086744393452879886