spring boot 是一个基于 spring 框架的轻量级开源框架,它的出现极大地简化了 spring 应用的搭建和开发。在开发过程中,接口文档是非常重要的一环,它不仅方便开发者查看和理解接口的功能和参数,还能帮助前后端开发协同工作,提高开发效率。
Swagger 是一个 RESTful 接口文档的规范和工具集,它的目标是统一 RESTful 接口文档的格式和规范。在开发过程中,接口文档是非常重要的一环,它不仅方便开发者查看和理解接口的功能和参数,还能帮助前后端开发协同工作,提高开发效率。Spring Boot 可以集成 Swagger 来自动生成接口文档。通过使用注解描述接口,Swagger能够自动生成接口文档。
Swagger 的官方网站是 https://swagger.io/,我们可以在这里下载最新版本的 Swagger。
解压下载的 Swagger 到指定目录即可,这一安装过程相当简单。在解压后的目录中,我们可以找到 swagger-ui.html 页面,这个页面就是 Swagger 的 UI 界面。
在编写接口时,我们需要使用 Swagger 的注解来描述接口信息。常用的注解包括:
@Api:用于描述接口的类或接口
@ApiOperation:用于描述接口的方法
@ApiParam:用于描述接口的参数
@ApiModel:用于描述数据模型
@ApiModelProperty:用于描述数据模型的属性
例如,我们编写一个简单的接口:
@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 文件中添加以下依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>在 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 注释来定义 API 的响应参数。例如,我们可以编写一个 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 中显示认证按钮。
在API文档中,可能有些参数包含敏感信息,因此需要保护这些信息不被公示。我们可以使用 @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 表示忽略该参数。
以上就是SpringBoot整合Swagger的方法是什么的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号