SpringBoot2.7.14整合Swagger3.0的详细步骤及容易踩坑的地方

🧑‍💻作者名称:DaenCode
🎤作者简介:啥技术都喜欢捣鼓捣鼓,喜欢分享技术、经验、生活。
😎人生感悟:尝尽人生百味,方知世间冷暖。
📖所属专栏:SpringBoot实战


系列文章目录

以下是专栏部分内容,更多内容请前往专栏查看!

标题
一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码)
一张思维导图带你学会Springboot创建全局异常、自定义异常
一张思维导图带你打通SpringBoot自定义拦截器的思路
28个SpringBoot项目中常用注解,日常开发、求职面试不再懵圈
一张思维导图带你学会SpringBoot、Vue前后端分离项目线上部署
一张流程图带你学会SpringBoot结合JWT实现登录功能
一张思维导图带你学会使用SpringBoot中的Schedule定时发送邮件
一张思维导图带你学会使用SpringBoot异步任务实现下单校验库存
一张思维导图带你学会SpringBoot使用AOP实现日志管理功能

在这里插入图片描述


专栏推荐

  • 专门为Redis入门打造的专栏,包含Redis基础知识、基础命令、五大数据类型实战场景、key删除策略、内存淘汰机制、持久化机制、哨兵模式、主从复制、分布式锁等等内容。链接>>>>>>>>>《Redis从头学》
  • 专门为RabbitMQ入门打造的专栏,持续更新中。。。。。。。。链接>>>>>>>《图解RabbitMQ》

🌟引入依赖

<!--swagger ui接口文档依赖-->
       <dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-boot-starter</artifactId>
       </dependency>

🌟applicationproperties配置文件

Springfox MVC路径匹配是基于AntPathMatcher的,而Spring Boot 2.7.14基于PathPatternMatcher。可以查看WebMvcProperties类

在这里插入图片描述因此,修改mvc的匹配策略为ant_path_matcher。如果swagger与springboot匹配策略不一致则会有错误:

Failed to start bean ‘ documentationPluginsBootstrapper ‘ ; nested exception…

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

🌟配置类创建

@Component
@Data
@EnableOpenApi
public class SwaggerConfiguration {
    /**
     * 用户端接口文档
     * @return
     */
    @Bean
    public Docket webApiDoc(){
        return new Docket(DocumentationType.OAS_30)
                .groupName("用户端接口文档")
                .pathMapping("/")
                //定义是否开启swagger
                .enable(true)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("top.daencode"))
                //正则匹配请求路径,并分配至当前分组
                .paths(PathSelectors.ant("/api/**"))
                .build()
        //新版swagger3.0配置
                .globalRequestParameters(getGlobalRequestParameters())
                .globalResponses(HttpMethod.GET, getGlobalResponseMessage())
                .globalResponses(HttpMethod.POST, getGlobalResponseMessage());
    }
    /**
     * 管理端接口文档
     * @return
     */
    @Bean
    public Docket adminApiDoc(){
        return new Docket(DocumentationType.OAS_30)
                .groupName("管理端接口文档")
                .pathMapping("/")
                //定义是否开启swagger
                .enable(true)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("top.daencode"))
                //正则匹配请求路径,并分配至当前分组
                .paths(PathSelectors.ant("/api/**"))
                .build()
                .globalRequestParameters();
    }
    /**
     * 接口文档元数据信息
     * @return
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("xxx项目接口文档")
                .description("接口文档")
                .contact(new Contact("daencode","https:daencode.top","shoanjen@126.com"))
                .version("v1.0")
                .build();
    }
    /**
     * 生成全局通用请求参数
     * @return
     */
    private List<RequestParameter> getGlobalRequestParameters() {
        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameterBuilder()
                .name("token")
                .description("登录令牌")
                .in(ParameterType.HEADER)
                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                .required(false)
                .build());
//        可以配置多个
//        parameters.add(new RequestParameterBuilder()
//                .name("version")
//                .description("版本号")
//                .required(true)
//                .in(ParameterType.HEADER)
//                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
//                .required(false)
//                .build());
        return parameters;
    }
    /**
     * 生成通用的接口文档响应信息
     * @return
     */
    private List<Response> getGlobalResponseMessage() {
        List<Response> responseList = new ArrayList<>();
        responseList.add(new ResponseBuilder().code("4xx").description("请求错误,根据code和msg检查").build());
        return responseList;
    }
}

注意

  • 使用@EnableOpenApi开启swagger3.0。
  • apis(RequestHandlerSelectors.basePackage(“top.daencode”)):注意修改此处生效的包名。
  • .paths(PathSelectors.ant(“/api/**”)):修改接口的通用路径。
  • parameters.add:生成全局通用配置参数,比如说用户登录的token。

🌟常用注解

注解描述
@Api用于描述整个API接口的信息,包括API的标题、描述等。
@ApiOperation用于描述单个接口的操作信息,包括接口的HTTP方法、路径、描述等。
@ApiParam用于描述接口参数的信息,包括参数名、类型、描述等。
@ApiModel用于描述接口返回结果或请求体的模型信息。
@ApiModelProperty用于描述模型属性的信息,包括属性名、类型、描述等。
@ApiIgnore用于忽略某个API接口,使其不在生成的文档中显示。
@ApiResponse用于描述接口的响应信息,包括响应码、描述、返回类型等。
@ApiResponses用于描述多个接口响应的信息,可以与@ApiResponse配合使用。

🌟具体用法

@ApiModel+@ApiModelProperty

@ApiModel("用户登录对象")
@Data
public class UserLogin {
    @ApiModelProperty(value = "用户名",example = "daencode")
    private String username;
    @ApiModelProperty(value = "密码",example = "123456")
    private String password;
    @ApiModelProperty(value = "验证码",example = "3425")
    private String captcha;
}

@Api+@ApiOperation+@ApiParam

@Api("用户模块")
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("login")
    @ApiOperation("用户登录")
    public JsonData login(@ApiParam("登录对象") @RequestBody UserLogin userLogin){
        //token为空则返回失败,否则返回成功
        String token=userService.login(userLogin);
        return token==null?JsonData.buildError("登录失败"):JsonData.buildSuccess(token);
    }
}


@ApiResponses+@ApiResponse

@ApiOperation("创建用户")
@ApiResponses(value = {
        @ApiResponse(code = 201, message = "用户创建成功", response = User.class),
        @ApiResponse(code = 400, message = "请求参数有误"),
        @ApiResponse(code = 401, message = "未授权访问"),
        @ApiResponse(code = 500, message = "服务器内部错误")
})
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
    // ...
}


效果查看

1.前往postman发起接口请求测试。
在这里插入图片描述
2.访问:http://localhost:8080/swagger-ui/index.html,查看接口文档。
在这里插入图片描述


🌟写在最后

有关于SpringBoot2.7.14整合Swagger3.0的详细步骤及容易踩坑的地方到此就结束了。感谢大家的阅读,希望大家在评论区对此部分内容散发讨论,便于学到更多的知识。


请添加图片描述

  • 19
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 33
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

DaenCode

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

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

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

打赏作者

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

抵扣说明:

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

余额充值