经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
手把手带你上手swagger3
来源:cnblogs  作者:Scotyzh  时间:2024/1/24 10:17:31  对本文有异议

配置POM

只需要加一个依赖,并且要注意,swagger3在springboot2.5版本以上会出现问题

  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-boot-starter</artifactId>
  4. <version>3.0.0</version>
  5. </dependency>

如果高于2.5版本会报错:

  1. org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

解决方法是降低spring的版本到2.5.x以下,或者是降低swagger版本到3以下,或者是在SwaggerConfig注解上标注@EnableWebMvc

配置例子

配置SwaggerConfig

  1. @Configuration
  2. @EnableSwagger2
  3. @Slf4j
  4. @EnableWebMvc
  5. public class SwaggerConfig {
  6. @Bean
  7. public Docket docket(Environment environment) {
  8. return new Docket(DocumentationType.SWAGGER_2)
  9. .apiInfo(apiInfo()) // 文档基础配置
  10. .select()
  11. .paths(PathSelectors.regex("(?!/error.*).*")) //加这行去除掉basic error controller接口
  12. .build();
  13. }
  14. private ApiInfo apiInfo() {
  15. return new ApiInfoBuilder()
  16. .title("xx平台接口文档")
  17. .build();
  18. }
  19. }

配置实体类

  1. @ApiModel(value = "UsersDTO", description = "UsersDTO实体类")
  2. @Data
  3. @AllArgsConstructor
  4. @NoArgsConstructor
  5. @Builder
  6. public class UserDTO {
  7. @ApiModelProperty(value = "First name", example = "Jean")
  8. private String firstname;
  9. @ApiModelProperty(value = "Last name", example = "ab")
  10. private String lastname;
  11. @ApiModelProperty(value = "CardInfo")
  12. private CardInfo cardInfo;
  13. }

可以看到这个类存在CardInfo嵌套类,对嵌套类的配置同上:

  1. @ApiModel(value = "CardInfo", description = "CardInfo实体类")
  2. @Data
  3. public class CardInfo {
  4. @ApiModelProperty(value = "cardName", example = "card")
  5. String cardName;
  6. }

注意:实体类的字段都需要有get方法,不然会失效,这里统一使用lombok的@Data解决

配置Controller类

  1. @RestController
  2. @Api(tags = "用户管理接口")
  3. @RequestMapping("/users")
  4. public class UsersController {
  5. @Autowired
  6. private UsersService usersService;
  7. @ApiOperation(value = "用户注册",notes = "传入用户信息进行注册")
  8. @PostMapping(value = "/register")
  9. public AjaxResult<Users> register(@RequestBody Users users) throws IOException {
  10. usersService.save(users);
  11. return AjaxResult.success(users);
  12. }
  13. }

这里面的返回值AjaxResult需要定义好泛型,在返回值初定义类型

AjaxResult类

  1. @ApiModel("API通用返回数据")
  2. @Data
  3. public class AjaxResult<T> {
  4. @ApiModelProperty(value = "状态码", example = "200")
  5. private final int code;
  6. @ApiModelProperty(value = "返回消息", example = "success")
  7. private final String message;
  8. @ApiModelProperty("数据对象")
  9. private final T data;
  10. public AjaxResult(int code, String message, T data) {
  11. this.code = code;
  12. this.message = message;
  13. this.data = data;
  14. }
  15. public int getCode() {
  16. return code;
  17. }
  18. public String getMessage() {
  19. return message;
  20. }
  21. public T getData() {
  22. return data;
  23. }
  24. public static <T> AjaxResult<T> success() {
  25. return new AjaxResult<>(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMessage(), null);
  26. }
  27. public static <T> AjaxResult<T> success(String message) {
  28. return new AjaxResult<>(ResultCodeEnum.SUCCESS.getCode(), message, null);
  29. }
  30. public static <T> AjaxResult<T> success(T data) {
  31. return new AjaxResult<>(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMessage(), data);
  32. }
  33. public static <T> AjaxResult<T> success(String message, T data) {
  34. return new AjaxResult<>(ResultCodeEnum.SUCCESS.getCode(), message, data);
  35. }
  36. public static <T> AjaxResult<T> failed() {
  37. return new AjaxResult<>(ResultCodeEnum.FAILED.getCode(), ResultCodeEnum.FAILED.getMessage(), null);
  38. }
  39. public static <T> AjaxResult<T> failed(String message) {
  40. return new AjaxResult<>(ResultCodeEnum.FAILED.getCode(), message, null);
  41. }
  42. public static <T> AjaxResult<T> failed(ResultCodeEnum resultCodeEnum) {
  43. return new AjaxResult<>(resultCodeEnum.getCode(), resultCodeEnum.getMessage(), null);
  44. }
  45. public static <T> AjaxResult<T> failed(String message, T data) {
  46. return new AjaxResult<>(ResultCodeEnum.FAILED.getCode(), message, data);
  47. }
  48. public static <T> AjaxResult<T> failed(ResultCodeEnum resultCodeEnum, T data) {
  49. return new AjaxResult<>(resultCodeEnum.getCode(), resultCodeEnum.getMessage(), data);
  50. }
  51. }

效果

image-20240123200557956

swagger有关的常用注解

  1. @Api 注解

    @Api 注解用于描述整个 API,通常放在控制器类上,一般使用tags注解就可以

    1. @Api(tags = "User API")
    2. @RestController
    3. @RequestMapping("/api/users")
    4. public class UserController {
    5. // ...
    6. }
  2. @ApiOperation 注解

    @ApiOperation 注解用于描述具体的 API 操作,通常放在控制器方法上

    1. @ApiOperation(
    2. value = "Get user by ID",
    3. notes = "Get user details by providing user ID"
    4. )
    5. @GetMapping("/{userId}")
    6. public ResponseEntity<User> getUserById(@PathVariable Long userId) {
    7. // Implementation to get user by ID
    8. }
  3. @ApiParam 注解

    @ApiParam 注解用于描述方法参数,提供参数的名称、描述等信息。

    1. @GetMapping("/{userId}")
    2. public ResponseEntity<User> getUserById(
    3. @ApiParam(name = "userId", value = "ID of the user", required = true)
    4. @PathVariable Long userId) {
    5. // Implementation to get user by ID
    6. }
  4. @ApiResponse@ApiResponses 注解

    这两个注解用于描述操作的响应信息,作用在方法上。

    1. @ApiResponses({
    2. @ApiResponse(code = 200, message = "Successful operation", response = String.class),
    3. @ApiResponse(code = 404, message = "User not found", response = String.class),
    4. })
    5. @GetMapping("/{userId}")
    6. public ResponseEntity<User> getUserById(@PathVariable Long userId) {
    7. // Implementation to get user by ID
    8. }
  5. @ApiModel@ApiModelProperty 注解

    这两个注解用于描述数据模型,通常放在实体类上。其中,下述的example可以实现在swagger页面调接口的默认值,并且如果导入到如eolink这种api管理工具,这个默认值也会填充进去。

    1. @ApiModel(description = "User information")
    2. public class User {
    3. @ApiModelProperty(value = "User ID", example = "ab")
    4. private Long id;
    5. @ApiModelProperty(value = "User name", example = "cd")
    6. private String name;
    7. // Getters and setters
    8. }
  6. @ApiIgnore 注解

    @ApiIgnore 注解用于标记不想在 Swagger 文档中显示的类、方法。

    1. @ApiIgnore
    2. public class IgnoredController {
    3. // ...
    4. }

    上述的 IgnoredController 类及其所有方法将被忽略。

  7. @ApiParamImplicit 注解

    @ApiParamImplicit 注解用于表示参数,需要被包含在注解@ApiImplicitParams之内。

    1. @ApiImplicitParams({
    2. @ApiImplicitParam(name = "userId", value = "ID of the user", required = true, dataType = "long", paramType = "path"),
    3. })
    4. @GetMapping("/{userId}")
    5. public ResponseEntity<User> getUserById(
    6. @PathVariable Long userId) {
    7. // Implementation to get user by ID
    8. }

导出json格式的swagger文档

点击主页这个地方

image-20240123202246160

按F12,在源代码里面的v2-api-docs里面右键另存为

image-20240123202423948

输入名称和后缀进行保存

image-20240123202516635

导入eolink

点api向下的箭头,再选swagger

image-20240123202614038

导入成功后可以看到,传参和返回值都能被正确识别和导入,包括传参的默认值也有

image-20240123203040508

原文链接:https://www.cnblogs.com/scottyzh/p/17983987

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号