【接口篇】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", "732171109@qq.com"))
        .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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Strive_MY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值