
✅作者简介:2022年博客新星 第八。热爱国学的Java后端开发者,修心和技术同步精进。
🍎个人主页:Java Fans的博客
🍊个人信条:不迁怒,不贰过。小知识,大智慧。
💞当前专栏:SpringBoot 框架从入门到精通
✨特色专栏:国学周更-心性养成之路
🥭本文内容:Spring Boot 整合 Swagger 教程详解

Spring Boot 是一个基于 Spring 框架的轻量级开源框架,它的出现极大地简化了 Spring 应用的搭建和开发。在开发过程中,接口文档是非常重要的一环,它不仅方便开发者查看和理解接口的功能和参数,还能帮助前后端开发协同工作,提高开发效率。本文将介绍如何在 Spring Boot 中使用 Swagger 来实现接口文档的自动生成。
Swagger 是一个 RESTful 接口文档的规范和工具集,它的目标是统一 RESTful 接口文档的格式和规范。在开发过程中,接口文档是非常重要的一环,它不仅方便开发者查看和理解接口的功能和参数,还能帮助前后端开发协同工作,提高开发效率。在 Spring Boot 中,我们可以通过集成 Swagger 来实现接口文档的自动生成。Swagger 通过注解来描述接口,然后根据这些注解自动生成接口文档。
Swagger 的官方网站是 https://swagger.io/,我们可以在这里下载最新版本的 Swagger。
安装 Swagger 非常简单,只需要将下载的 Swagger 解压到指定目录即可。在解压后的目录中,我们可以找到 swagger-ui.html 页面,这个页面就是 Swagger 的 UI 界面。
在编写接口时,我们需要使用 Swagger 的注解来描述接口信息。常用的注解包括:
例如,我们编写一个简单的接口:
@RestController
@Api(tags = "用户接口")
public class UserController {
 
    @GetMapping("/user/{id}")
    @ApiOperation(value = "根据 ID 获取用户信息")
    public User getUserById(@ApiParam(value = "用户 ID", required = true) @PathVariable Long id) {
        // 根据 ID 查询用户信息
    }
}
 
在上面的代码中,@Api表示该类是一个用户接口,@ApiOperation 表示该方法是获取用户信息的接口,@ApiParam 表示该参数是用户 ID,@PathVariable 表示该参数是路径参数。
在 Spring Boot 中,我们可以通过添加 Swagger 相关的依赖来启用 Swagger。
我们可以在 pom.xml 文件中添加以下依赖:
io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2 
在 Spring Boot 中,我们还需要添加配置类来配置 Swagger。配置类的代码如下:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
 
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口文档")
                .description("接口文档")
                .version("1.0.0")
                .build();
    }
}
 
在上面的代码中,@Configuration 表示该类是一个配置类,@EnableSwagger2 表示启用 Swagger。在 api() 方法中,我们通过 `select() 方法配置扫描的包路径,paths() 方法配置接口的访问路径,apiInfo() 方法配置接口文档的相关信息。
启动 Spring Boot 应用后,我们可以在浏览器中访问 http://localhost:8080/swagger-ui.html 来查看接口文档。在 Swagger UI 页面中,我们可以看到所有的接口信息,包括接口名称、请求方式、请求路径、请求参数、响应参数等。
我们可以使用 @ApiModel 和 @ApiModelProperty 注解来描述数据模型和属性。例如,我们可以编写一个 User 类,并在类上使用 @ApiModel 和
@ApiModelProperty 注解来描述该数据模型:
@ApiModel(description = "用户信息")
public class User {
 
    @ApiModelProperty(value = "用户 ID", example ="1") 
    private Long id;
	@ApiModelProperty(value = "用户名", example = "张三")
	private String username;
	@ApiModelProperty(value = "密码", example = "123456")
	private String password;
	// 省略 getter 和 setter 方法
}
 
在上面的代码中,@ApiModel 表示该类是一个数据模型,@ApiModelProperty 表示该属性是数据模型的一个属性,value 属性表示属性的描述,example 属性表示属性的示例值。
我们可以使用 @ApiModel 和 @ApiModelProperty 注解来描述枚举类型。例如,我们可以编写一个 Gender 枚举类型,并在枚举值上使用 @ApiModelProperty 注解来描述该枚举值:
@ApiModel(description = "性别") public enum Gender {
@ApiModelProperty(value = "男")
MALE,
@ApiModelProperty(value = "女")
FEMALE;
}
 
在上面的代码中,@ApiModel 表示该枚举类型是一个描述性别的枚举类型,@ApiModelProperty 表示该枚举值是描述男性的枚举值或描述女性的枚举值。
我们可以使用 @ApiResponses 和 @ApiResponse 注解来描述接口的响应参数。例如,我们可以编写一个 getUserById() 方法,并在方法上使用 @ApiResponses 和 @ApiResponse 注解来描述该方法的响应参数:
@GetMapping("/user/{id}")
@ApiOperation(value = "根据 ID 获取用户信息") 
@ApiResponses({ @ApiResponse(code = 200, message = "请求成功", response = User.class), 
@ApiResponse(code = 404, message = "用户不存在") }) 
public User getUserById(@ApiParam(value = "用户 ID", required = true) @PathVariable Long id) 
{ 
	// 根据 ID 查询用户信息 
}
 
在上面的代码中,@ApiResponses 表示该方法的响应参数,@ApiResponse 表示该响应参数的描述,code 属性表示响应码,message 属性表示响应消息,response 属性表示响应的数据模型。
我们可以在配置类中使用 globalOperationParameters() 方法来配置全局参数。例如,我们可以配置一个全局的 Authorization 参数,用于授权:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
 
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(Arrays.asList(
                        new ParameterBuilder()
                                .name("Authorization")
                                .description("授权")
                                .modelRef(new ModelRef("string"))
                                .parameterType("header")
                                .required(false)
                                .build()
                ))
                .apiInfo(apiInfo());
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口文档")
                .description("接口文档")
                .version("1.0.0")
                .build();
    }
 
}
 
在上面的代码中,我们通过 globalOperationParameters() 方法来配置一个全局的 Authorization 参数,用于授权。
我们可以在配置类中使用 securitySchemes() 方法来配置安全协议。例如,我们可以配置一个 Bearer Token 安全协议:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
 
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(Arrays.asList(
                        new ApiKey("Bearer", "Authorization", "header")
                ))
                .apiInfo(apiInfo());
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口文档")
                .description("接口文档")
                .version("1.0.0")
                .build();
    }
 
}
 
在上面的代码中,我们通过 securitySchemes() 方法来配置一个 Bearer Token 安全协议。
我们可以在配置类中使用 securityContexts() 方法来配置安全上下文。例如,我们可以配置一个安全上下文,用于在 Swagger UI 中显示认证按钮:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
 
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(Arrays.asList(
                        new ApiKey("Bearer", "Authorization", "header")
                ))
                .securityContexts(Collections.singletonList(
                        SecurityContext.builder()
                                .securityReferences(Collections.singletonList(
                                        new SecurityReference("Bearer", new AuthorizationScope[0])
                                ))
                                .build()
                ))
                .apiInfo(apiInfo());
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口文档")
                .description("接口文档")
                .version("1.0.0")
                .build();
    }
 
}
 
在上面的代码中,我们通过 securityContexts() 方法来配置一个安全上下文,用于在 Swagger UI 中显示认证按钮。
在接口中,有些参数可能是敏感信息,我们不希望在接口文档中显示。我们可以使用 @ApiIgnore 注解来忽略这些参数。例如,我们可以在 User 类中使用 @ApiIgnore 注解来忽略密码参数:
@ApiModel(description = "用户信息")
public class User {
 
    @ApiModelProperty(value = "用户 ID", example = "1")
    private Long id;
 
    @ApiModelProperty(value = "用户名", example = "张三")
    private String username;
 
    @ApiModelProperty(hidden = true)
    @ApiIgnore
    private String password;
 
    // 省略 getter 和 setter 方法
}
 
在上面的代码中,@ApiModelProperty(hidden = true) 表示该参数是隐藏的,@ApiIgnore 表示忽略该参数。
通过集成 Swagger,我们可以方便地生成接口文档,使得前后端开发协同更加高效。在使用 Swagger 时,我们需要注意以下几点:
码文不易,本篇文章就介绍到这里,如果想要学习更多Java系列知识,点击关注博主,博主带你零基础学习Java知识。与此同时,对于日常生活有困扰的朋友,欢迎阅读我的第四栏目:《国学周更—心性养成之路》,学习技术的同时,我们也注重了心性的养成。
