大型医疗挂号微服务“马上好医”医疗项目(5)Swagger的使用

Swagger的简单介绍

Swagger 是一个 RESTful 接口文档的规范和工具集,它的目标是统一 RESTful 接口文档的格式和规范。在开发过程中,接口文档是非常重要的一环,它不仅方便开发者查看和理解接口的功能和参数,还能帮助前后端开发协同工作,提高开发效率。在 Spring Boot 中,我们可以通过集成 Swagger 来实现接口文档的自动生成。Swagger 通过注解来描述接口,然后根据这些注解自动生成接口文档。

同类型的产品

ApiDoc:

ApiDoc定位: ApiDoc=Postman+Swagger+mock+Jmeter,是一款集 API设计,接口文档管理、代码生成、API 调试、API mock,API 自动化为一体的接口一站式协作平台。

也就是说,它比 swagger 的的功能要更加广泛和齐全,不仅通过可视化界面设计接口生成接口文档和项目代码,

还打通了接口数据的协作流程,一套接口数据,设计出来可以给前端、测试使用,减少了再不同系统间切换、导入导出数据、更新维护的麻烦。

缺点:太繁琐,因为支持了太多的功能,并且也不符合注解式开发的规范,需要写大量的文档类东西。

Swagger的简单上手:

依赖:

<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>

配置:

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();
    }
}

注解:

  • @Api:用于描述接口的类或接口
  • @ApiOperation:用于描述接口的方法
  • @ApiParam:用于描述接口的参数
  • @ApiModel:用于描述数据模型
  • @ApiModelProperty:用于描述数据模型的属性
  • @ApiImplicitParams:方法参数的说明
  • @ApiImplicitParam:用于指定单个参数的说明
  • @ApiResponses:方法返回值的说明
  • @ApiResponse:用于指定单个参数的说明

注解属性:

  • value:url的路径值
  • tags :如果设置这个值、value的值会被覆盖
  • description:对api资源的描述
  • basePath:基本路径
  • position:如果配置多个Api 想改变显示的顺序位置
  • produces :“application/json, application/xml”
  • consumes:“application/json, application/xml”
  • protocols : http, https, ws, wss.
  • authorizations: 高级特性认证时配置
  • hidden :配置为true ,将在文档中隐藏

查看接口文档

启动 Spring Boot 应用后,我们可以在浏览器中访问http://localhost:8080/swagger-ui.html来查看接口文档。在 Swagger UI 页面中,我们可以看到所有的接口信息,包括接口名称、请求方式、请求路径、请求参数、响应参数等。

Swagger的用法:

1、描述数据模型

我们可以使用 @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 属性表示属性的示例值。

2、描述枚举类型

我们可以使用 @ApiModel 和 @ApiModelProperty 注解来描述枚举类型。例如,我们可以编写一个 Gender 枚举类型,并在枚举值上使用 @ApiModelProperty 注解来描述该枚举值:

@ApiModel(description = "性别") public enum Gender {

@ApiModelProperty(value = "男")
MALE,

@ApiModelProperty(value = "女")
FEMALE;
}

在上面的代码中,@ApiModel 表示该枚举类型是一个描述性别的枚举类型,@ApiModelProperty 表示该枚举值是描述男性的枚举值或描述女性的枚举值。

3、描述响应参数

我们可以使用 @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 属性表示响应的数据模型。

五、Swagger 的进阶使用

1、配置全局参数

我们可以在配置类中使用 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 参数,用于授权。

2、配置安全协议

我们可以在配置类中使用 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 安全协议。

3、配置安全上下文

我们可以在配置类中使用 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 中显示认证按钮。

4、配置忽略参数

在接口中,有些参数可能是敏感信息,我们不希望在接口文档中显示。我们可以使用 @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 时,我们需要注意以下几点:

  • 使用注解来描述接口信息,包括接口名称、请求方式、请求路径、请求参数、响应参数等;
  • 在配置类中配置 Swagger,包括扫描的包路径、接口文档信息、全局参数、安全协议、安全上下文等;
  • 描述数据模型、枚举类型、响应参数等信息,方便开发者查看和理解接口的功能和参数;
  • 在需要时使用 @ApiIgnore 注解来忽略敏感参数的显示。
  • 最后,需要注意的是,Swagger 只是一种规范和工具集,它并不能取代单元测试和集成测试等其他测试方式。在开发过程中,我们需要综合使用各种测试方式,保证软件的质量和稳定性。
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Add小兵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值