Java教程

手把手带你上手swagger3

本文主要是介绍手把手带你上手swagger3,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

配置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. @ApiModel 和 @ApiModelProperty 注解:

    通常,@ApiModel 注解会与 @ApiModelProperty 注解一起使用,前者用于描述类,后者用于描述类中的属性。其中,下述的example可以实现在swagger页面调接口的默认值,并且如果导入到如eolink这种api管理工具,这个默认值也会填充进去。

    @ApiModel(value = "User", description = "User information")
    public class User {
        @ApiModelProperty(value = "用户名", example = "clt")
        private String userName;
    }
    
  2. @ApiIgnore 注解

    @ApiIgnore 注解用于忽略特定的类或方法,不会在生成的文档中显示。

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

    在上面的例子中,IgnoredController 类及其所有方法将被忽略。

  3. @ApiOperation@ApiResponse@ApiResponses注解

    在方法级别上添加 @ApiOperation 注解,用于描述特定操作的信息,如操作的摘要、描述、响应等。@ApiResponse@ApiResponses 这两个注解用于描述操作的响应信息,@ApiResponses注解包含了多个@ApiResponse` 注解,用于描述不同的响应情况。

    @ApiOperation(
        summary = "Get user by ID",
        description = "Get user details by providing user ID"
    )
    @ApiResponses({
        @ApiResponse(
            responseCode = "200",
            description = "Successful operation",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = User.class)
            )
        ),
        @ApiResponse(
            responseCode = "404",
            description = "User not found",
            content = @Content
        )
    })
    @GetMapping("/{userId}")
    public ResponseEntity<User> getUserById(@PathVariable Long userId) {
        // Implementation to get user by ID
    }
    

    在上面的例子中,@ApiOperation 注解用于描述获取用户信息的操作。

  4. @ApiParam 注解

    在方法的参数上添加 @ApiParam 注解,用于描述参数的信息,如名称、描述、是否必需等。

    @GetMapping("/{userId}")
    public ResponseEntity<User> getUserById(
        @ApiParam(name = "userId", description = "ID of the user", required = true)
        @PathVariable Long userId) {
        // Implementation to get user by ID
    }
    

    @ApiParam 注解用于描述 userId 参数。

导出json格式的swagger文档

点击主页这个地方

image-20240123202246160

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

image-20240123202423948

输入名称和后缀进行保存

image-20240123202516635

点api向下的箭头,再选swagger

image-20240123202614038

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

image-20240123203040508

这篇关于手把手带你上手swagger3的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!