手把手带你上手swagger3

时间:2024-01-24 18:00:38

配置POM

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

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

如果高于2.5版本会报错:

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

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

配置例子

配置SwaggerConfig

@Configuration
@EnableSwagger2
@Slf4j
@EnableWebMvc
public class SwaggerConfig {

    @Bean
    public Docket docket(Environment environment) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()) // 文档基础配置
                .select()
                .paths(PathSelectors.regex("(?!/error.*).*"))  //加这行去除掉basic error controller接口
                .build();

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("xx平台接口文档")
                .build();
    }

}

配置实体类

@ApiModel(value = "UsersDTO", description = "UsersDTO实体类")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserDTO {

    @ApiModelProperty(value = "First name", example = "Jean")
    private String firstname;

    @ApiModelProperty(value = "Last name", example = "ab")
    private String lastname;

    @ApiModelProperty(value = "CardInfo")
    private CardInfo cardInfo;

}

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

@ApiModel(value = "CardInfo", description = "CardInfo实体类")
@Data
public class CardInfo {

    @ApiModelProperty(value = "cardName", example = "card")
    String cardName;
}

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

配置Controller类

@RestController
@Api(tags = "用户管理接口")
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    @ApiOperation(value = "用户注册",notes = "传入用户信息进行注册")
    @PostMapping(value = "/register")
    public AjaxResult<Users> register(@RequestBody Users users) throws IOException {
        usersService.save(users);
        return AjaxResult.success(users);
    }

}

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

AjaxResult类

@ApiModel("API通用返回数据")
@Data
public class AjaxResult<T> {

    @ApiModelProperty(value = "状态码", example = "200")
    private final int code;

    @ApiModelProperty(value = "返回消息", example = "success")
    private final String message;

    @ApiModelProperty("数据对象")
    private final T data;

    public AjaxResult(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }

    public static <T> AjaxResult<T> success() {
        return new AjaxResult<>(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMessage(), null);
    }

    public static <T> AjaxResult<T> success(String message) {
        return new AjaxResult<>(ResultCodeEnum.SUCCESS.getCode(), message, null);
    }

    public static <T> AjaxResult<T> success(T data) {
        return new AjaxResult<>(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMessage(), data);
    }

    public static <T> AjaxResult<T> success(String message, T data) {
        return new AjaxResult<>(ResultCodeEnum.SUCCESS.getCode(), message, data);
    }

    public static <T> AjaxResult<T> failed() {
        return new AjaxResult<>(ResultCodeEnum.FAILED.getCode(), ResultCodeEnum.FAILED.getMessage(), null);
    }

    public static <T> AjaxResult<T> failed(String message) {
        return new AjaxResult<>(ResultCodeEnum.FAILED.getCode(), message, null);
    }

    public static <T> AjaxResult<T> failed(ResultCodeEnum resultCodeEnum) {
        return new AjaxResult<>(resultCodeEnum.getCode(), resultCodeEnum.getMessage(), null);
    }

    public static <T> AjaxResult<T> failed(String message, T data) {
        return new AjaxResult<>(ResultCodeEnum.FAILED.getCode(), message, data);
    }

    public static <T> AjaxResult<T> failed(ResultCodeEnum resultCodeEnum, T data) {
        return new AjaxResult<>(resultCodeEnum.getCode(), resultCodeEnum.getMessage(), data);
    }
}

效果

image-20240123200557956

swagger有关的常用注解

  1. @Api 注解

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

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

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

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

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

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

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

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

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

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

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

    @ApiIgnore
    public class IgnoredController {
        // ...
    }
    

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

  7. @ApiParamImplicit 注解

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

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

导出json格式的swagger文档

点击主页这个地方

image-20240123202246160

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

image-20240123202423948

输入名称和后缀进行保存

image-20240123202516635

点api向下的箭头,再选swagger

image-20240123202614038

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

image-20240123203040508