Spring Boot 中使用 Swagger3.0.0 注解案例
- 2025-11-27 黑龙江
本文字数:9565 字
阅读完需:约 31 分钟
@ApiModel
@ApiModel
@ApiModel: 位置:用在返回对象类上 作用:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候) 参数说明:@ApiModel("description":"") description="描述实体的作用"
代码示例如下:
package com.swagger.bean;
import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;
@Data@AllArgsConstructor@NoArgsConstructor@ApiModel(description= "返回响应数据")public class User { @ApiModelProperty(name = "id", value = "用户ID") private Integer id; //姓名 @ApiModelProperty(name = "name", value = "用户姓名") private String name; //密码 @ApiModelProperty(name = "password", value = "用户密码") private String password;}
@ApiModelProperty
@ApiModelProperty
@ApiModelProperty: 位置:用在属性上 作用:描述一个model的属性 参数说明:@ApiModelProperty("value":"", "name":"", "required":"") value="参数说明" 描述参数的意义 name="参数名称" 参数的变量名 required=true 参数是否必选
代码示例如下:
package com.swagger.bean;
import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;
@Data@AllArgsConstructor@NoArgsConstructor@ApiModel(description= "返回响应数据")public class User { @ApiModelProperty(name = "id", value = "用户ID") private Integer id; //姓名 @ApiModelProperty(name = "name", value = "用户姓名") private String name; //密码 @ApiModelProperty(name = "password", value = "用户密码") private String password;}
网站效果展示:
<hr>
@ApiParam
@ApiParam
@ApiParam: 位置:用在请求方法、参数上 作用:对参数使用说明(如:说明 或是否必填等) 参数说明:@ApiParam("value":"", "name":"", "required":"") value="参数说明" 描述参数的意义 name="参数名称" 参数的变量名 required=true 参数是否必选
代码示例如下:
@PostMapping("/post")@ApiOperation(value = "新增用户", notes = "演示json参数是否接受成功")public Response postTest(@ApiParam(name = "user", value = "接收传递给后端接口的user对象参数") @RequestBody User user) {
网站效果展示:
<hr>
@ApiIgnore
@ApiIgnore
@ApiIgnore: 位置:用在类,方法,参数 作用:表示这个方法或者类被忽略,也就是在http://ip:port/swagger-ui.html上不显示 参数说明:无
代码示例如下:
@ApiIgnore@PutMapping("/update2")@ApiOperation(value = "修改用户2", notes = "演示json参数是否接受成功")public Response updateTest2(@ApiParam(name = "user", value = "接收传递给后端接口的user对象参数") @RequestBody User user) {
具体使用详情请看:Swagger中@ApiIgnore注解的使用
网站效果展示:
五、案例准备工作
0.项目目录
1.pom 依赖
<dependencies> <!--解决@RestController注解爆红--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.6.3</version> </dependency>
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> </dependency>
<!--Swagger版本--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency></dependencies>
2.创建 SwaggerConfig
package com.swagger.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.service.Contact;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;
/** * Swagger配置 */@Configuration@EnableOpenApi //@EnableOpenApi用于开启Swagger在 Spring Boot,可放在启动类上,也可放在这里,public class SwaggerConfig { /** * 配置Swagger的Docket的bean实例 */ @Bean public Docket docket() { return new Docket(DocumentationType.OAS_30) //(常用) groupName:分组 .groupName("标准接口") .apiInfo(apiInfo()) //(常用) select:通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现 .select() // /** * (常用) apis:过滤规则,可以自定义指定哪些接口生成文档 * RequestHandlerSelectors:配置要扫描接口的方式 * basePackage:指定要扫描的包 * any:扫面全部 * none:不扫描 * withClassAnnotation:扫描类上的注解(参数是类上注解的class对象) * withMethodAnnotation:扫描方法上的注解(参数是方法上的注解的class对象) */ .apis(RequestHandlerSelectors.basePackage("com.swagger.controller")) //(常用) apis:加了ApiOperation注解的类,生成接口文档// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) /** * (常用) paths:过滤路径 * PathSelectors:配置过滤的路径 * any:过滤全部路径 * none:不过滤路径 * ant:过滤指定路径:按照按照Spring的AntPathMatcher提供的match方法进行匹配 * regex:过滤指定路径:按照String的matches方法进行匹配 */ .paths(PathSelectors.any()) //(已淘汰)所有接口统一定义响应信息// .build().globalResponseMessage(); .build(); }
/** * 配置文档描述 * 访问地址:http://ip:port/swagger-ui.html */ private ApiInfo apiInfo() { return new ApiInfoBuilder() //文档标题 .title("标题:Spring Boot中使用Swagger3.0.0版本构建RESTful APIs") //文档描述 .description("描述:用户列表的CRUD") //团队链接 .termsOfServiceUrl("https://blog.csdn.net/a924382407/article/details/127842503") //联系人信息 .contact(new Contact("刘大猫", "https://blog.csdn.net/a924382407/article/details/127842503", "ldz924382407@163.com")) //API 版本 .version("1.0") .build(); }}
3.配置文件 application.yml
# 端口号server: port: 8016
# 设置SpringMVC的路径匹配策略spring: mvc: pathmatch: matching-strategy: ant_path_matcher
4.实体 bean
package com.swagger.bean;
import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;
/** * @Author 211145187 * @Date 2022/2/23 09:32 **/@Data@AllArgsConstructor@NoArgsConstructor@ApiModel(description= "返回响应数据")public class User { @ApiModelProperty(name = "id", value = "用户ID") private Integer id; //姓名 @ApiModelProperty(name = "name", value = "用户姓名") private String name; //密码 @ApiModelProperty(name = "password", value = "用户密码") private String password;}
5.后端接口 SwaggerController
package com.swagger.controller;
import com.swagger.bean.User;import com.swagger.response.PageResult;import com.swagger.response.Response;import io.swagger.annotations.Api;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiImplicitParams;import io.swagger.annotations.ApiOperation;import io.swagger.annotations.ApiParam;import io.swagger.annotations.ApiResponse;import io.swagger.annotations.ApiResponses;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import springfox.documentation.annotations.ApiIgnore;
import java.util.ArrayList;import java.util.List;
/** * 使用swagger,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务 * @Author 211145187 * @Date 2022/9/19 16:31 **/@RestController@RequestMapping("/swagger")@Api(tags = "用户管理")@Slf4jpublic class SwaggerController {
@GetMapping("/getList") @ApiOperation(value = "分页查询", notes = "分页查询的注意事项和备注", tags = {"说明该方法的作用1,说明该方法的作用2"}) @ApiImplicitParams({ @ApiImplicitParam(name = "pageNo", value = "当前页码,从1开始", paramType = "query", required = true, dataType="int") , @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", paramType = "query",required = true, dataType="int") , }) @ApiResponses({ @ApiResponse(code=400,message="请求参数及格式不对"), @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对") }) public Response<PageResult<User>> getList(@RequestParam int pageNo, @RequestParam int pageSize){ log.info("-getList-pageNo:{},pageSize:{}", pageNo, pageSize); List list = new ArrayList(); list.add(new User(1, "tom", "tom")); list.add(new User(2, "jerry", "jerry")); PageResult pageResult = new PageResult(); pageResult.setPageNum(pageNo); pageResult.setPageSize(pageSize); pageResult.setTotalPage(1); pageResult.setTotalCount(2); pageResult.setList(list); return Response.success(pageResult); }
@PostMapping("/post") @ApiOperation(value = "新增用户", notes = "演示json参数是否接受成功") public Response postTest(@ApiParam(name = "user", value = "接收传递给后端接口的user对象参数") @RequestBody User user) { log.info("-postTest-user:{}", user); return Response.success(user); }
@PutMapping("/update") @ApiOperation(value = "修改用户", notes = "演示json参数是否接受成功") public Response updateTest(@ApiParam(name = "user", value = "接收传递给后端接口的user对象参数") @RequestBody User user) { log.info("-postTest-user:{}", user); return Response.success(user); }
@ApiIgnore @PutMapping("/update2") @ApiOperation(value = "修改用户2", notes = "演示json参数是否接受成功") public Response updateTest2(@ApiParam(name = "user", value = "接收传递给后端接口的user对象参数") @RequestBody User user) { log.info("-postTest-user:{}", user); return Response.success(user); }
@DeleteMapping("/delete/{id}") @ApiOperation(value = "删除用户", notes = "演示json参数是否接受成功") public Response deleteTest(@ApiParam(name = "id", value = "接收的参数id") @PathVariable Integer id) { log.info("-deleteTest-id:{}", id); return Response.success(id); }}
6.返回对象 Response 介绍
java小工具util系列5:基础工具代码(Msg、PageResult、Response、常量、枚举)
7.启动类
package com.swagger;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
/** * 使用swagger,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务 * @Author 211145187 * @Date 2022/9/20 14:33 **/@SpringBootApplicationpublic class SwaggerApplication { public static void main(String[] args) { SpringApplication.run(SwaggerApplication.class, args); }}
六、运行结果展示
登录网址:http://localhost:8016/swagger-ui/index.html#/ 即可打开如下图的网站
七、注意事项说明
1.
@ApiOperation注解的tags属性尽量少用,因为 tags 属性会对接口重新分类,导致登录 swagger-ui 查看接口不清晰,具体如图,比如我只有一个 Controller 里面包含 4 个方法,按常理应该只有一个”用户管理“的接口说明,如果我使用 tags 属性,那么下方会多出一个 tags 属性标识过的重复的的接口说明(说白了就是有重复的显示,感觉不直观)。
2.SwaggerConfig 中无论是 Docket 属性还是 ApiInfoBuilder 属性、以及注解中属性都有很多,该案例只使用常用的几个属性,想了解其他属性请查看其他人博客了解即可。
3.Swagger2.x 版本中开启 Swagger 在 SpringBoot 项目的启动类或配置类中添加
@EnableSwagger2,而 Swagger3.0.0 版本中开启 Swagger 在 SpringBoot 项目的启动类或配置类中添加@EnableOpenApi4.
ApiInfo 基本信息参数介绍,可以看到,它提供了8 个可以配置属性,根据名字也能猜出其中的意思。version:API 版本
title:文档标题
description:文档描述
termsOfServiceUrl:团队链接
license:许可
licenseUrl:许可链接
contact:联系人信息
vendorExtensions:扩展信息
5.
问题:注解 @ApiParam 和 @ApiImplicitParams 都是作用在方法上,区别是啥?答案:他两互相都可以互为替代品,即描述参数用 @ApiParam 和 @ApiImplicitParams 都可以,只不过 @ApiImplicitParams 要和 @ApiImplicitParam 搭配使用。
八、报错场景说明
错误场景 1:org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.15.jar:5.3.15] at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.15.jar:5.3.15] at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.15.jar:5.3.15] at java.lang.Iterable.forEach(Iterable.java:75) ~[na:1.8.0_71] at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.15.jar:5.3.15] at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.15.jar:5.3.15] at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.15.jar:5.3.15] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.15.jar:5.3.15] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar:2.6.3] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) [spring-boot-2.6.3.jar:2.6.3] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) [spring-boot-2.6.3.jar:2.6.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) [spring-boot-2.6.3.jar:2.6.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) [spring-boot-2.6.3.jar:2.6.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) [spring-boot-2.6.3.jar:2.6.3] at com.swagger.SwaggerApplication.main(SwaggerApplication.java:14) [classes/:na]Caused by: java.lang.NullPointerException: null at springfox.documentation.spring.web.WebMvcPatternsRequestConditionWrapper.getPatterns(WebMvcPatternsRequestConditionWrapper.java:56) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0] at springfox.documentation.RequestHandler.sortedPaths(RequestHandler.java:113) ~[springfox-core-3.0.0.jar:3.0.0] at springfox.documentation.spi.service.contexts.Orderings.lambda$byPatternsCondition$3(Orderings.java:89) ~[springfox-spi-3.0.0.jar:3.0.0] at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) ~[na:1.8.0_71] at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:1.8.0_71] at java.util.TimSort.sort(TimSort.java:220) ~[na:1.8.0_71] at java.util.Arrays.sort(Arrays.java:1512) ~[na:1.8.0_71] at java.util.ArrayList.sort(ArrayList.java:1454) ~[na:1.8.0_71] at java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:387) ~[na:1.8.0_71] at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:1.8.0_71] at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:1.8.0_71] at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:1.8.0_71] at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:1.8.0_71] at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482) ~[na:1.8.0_71] at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_71] at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_71] at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_71] at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_71] at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:81) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0] at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_71] at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374) ~[na:1.8.0_71] at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_71] at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_71] at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_71] at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_71] at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_71] at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.withDefaults(AbstractDocumentationPluginsBootstrapper.java:107) ~[springfox-spring-web-3.0.0.jar:3.0.0] at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.buildContext(AbstractDocumentationPluginsBootstrapper.java:91) ~[springfox-spring-web-3.0.0.jar:3.0.0] at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.bootstrapDocumentationPlugins(AbstractDocumentationPluginsBootstrapper.java:82) ~[springfox-spring-web-3.0.0.jar:3.0.0] at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:100) ~[springfox-spring-web-3.0.0.jar:3.0.0] at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.15.jar:5.3.15] ... 14 common frames omitted
错误原因:SpinrgBoot 版本过高导致,比如我的 SpringBoot 版本 2.7.3,它使用的 Spring 版本 5.3.22 ,而 Spring5.x 版本中 SpringMVC 默认路径匹配策略从 AntPathMatcher 更改为 PathPatternParser
解决方案:针对原因 2,解决办法是切换回原先的 AntPathMatcher,即在 application.yml 中配置 spring:mvc:pathmatch:matching-strategy: ant_path_matcher
也可以查看其他人的博客了解详情:(已解决)Failed to start bean ‘documentationPluginsBootstrapper’
刘大猫
还未添加个人签名 2022-08-23 加入
还未添加个人简介







评论