Java 集成 Swagger 组件

一:简介

  Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

二:集成swagger

在 pom.xml 文件中引入 Swagger 依赖包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

在启动的 Application 类中加上 @EnableOpenApi 注解

@EnableOpenApi
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

访问:http://localhost:8080/swagger-ui/index.html 查看接口文档

如果启动时报错,请在 application.yml 文件中加入以下内容:

spring:
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER

注解

1、@Api

@Api 注解用于标注一个Controller(Class)。在默认情况下,Swagger-Core只会扫描解析具有@Api注解的类,而会自动忽略其他类别资源(JAX-RS endpoints,Servlets等等)的注解。

主要属性如下:

属性 描述
value url的路径值
tags 如果设置这个值、value的值会被覆盖
description 对api资源的描述
basePath 基本路径可以不配置
position 如果配置多个Api 想改变显示的顺序位置
produces For example, “application/json, application/xml”
consumes For example, “application/json, application/xml”
protocols Possible values: http, https, ws, wss.
authorizations 高级特性认证时配置
hidden 配置为true 将在文档中隐藏
@Controller
@RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
@Api(value = "/pet", description = "Operations about pets")
public class PetController {

}

2、@ApiOperation

@ApiOperation 注解在用于对一个操作或HTTP方法进行描述。具有相同路径的不同操作会被归组为同一个操作对象。不同的HTTP请求方法及路径组合构成一个唯一操作。

主要属性:

属性 描述
value url的路径值
tags 如果设置这个值、value的值会被覆盖
description 对api资源的描述
basePath 基本路径可以不配置
position 如果配置多个Api 想改变显示的顺序位置
produces For example, “application/json, application/xml”
consumes For example, “application/json, application/xml”
protocols Possible values: http, https, ws, wss.
authorizations 高级特性认证时配置
hidden 配置为true 将在文档中隐藏
response 返回的对象
responseContainer 这些对象是有效的 “List”, “Set” or “Map”.,其他无效
httpMethod “GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”
code http的状态码 默认 200
extensions 扩展属性
@RequestMapping(value = "/order/{orderId}", method = GET)
@ApiOperation(
    value = "Find purchase order by ID",
    notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
    response = Order.class,
    tags = { "Pet Store" })
public ResponseEntity<Order> getOrderById(@PathVariable("orderId") String orderId)
    throws NotFoundException {
    Order order = storeData.get(Long.valueOf(orderId));
    if (null != order) {
        return ok(order);
    } else {
        throw new NotFoundException(404, "Order not found");
    }
}

3、@ApiParam

@ApiParam作用于请求方法上,定义api参数的注解。

主要属性:

属性 描述
name 属性名称
value 属性值
defaultValue 默认属性值
allowableValues 可以不配置
required 是否属性必填
access 不过多描述
allowMultiple 默认为false
hidden 隐藏该属性
example 举例子
public ResponseEntity<Order> getOrderById(
    @ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true)
    @PathVariable("orderId") String orderId){

}

4、@ApiImplicitParams、@ApiImplicitParam

@ApiImplicitParams@ApiImplicitParam也可以定义参数.

  • @ApiImplicitParams:用在请求的方法上,包含一组参数说明
  • @ApiImplicitParam:对单个参数的说明

主要属性:

属性 描述
name 参数名
value 参数的说明、描述
required 参数是否必须必填
paramType 参数放在哪个地方 query –> 请求参数的获取:@RequestParam header –> 请求参数的获取:@RequestHeader path(用于restful接口)–> 请求参数的获取:@PathVariable body(请求体)–> @RequestBody User user form(普通表单提交)
dataType 参数类型,默认String,其它值dataType=”Integer”
defaultValue 参数的默认值
@ApiImplicitParams({
    @ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
    @ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
    @ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})
@PostMapping("/login")
public JsonResult login(@RequestParam String mobile, @RequestParam String password,
                        @RequestParam Integer age){
    //...
    return JsonResult.ok(map);
}

5、@ApiResponses、@ApiResponse

@ApiResponses@ApiResponse进行方法返回对象的说明。

主要属性:

属性 描述
code 数字,例如400
message 信息,例如”请求参数没填好”
response 抛出异常的类
@ApiResponses({
    @ApiResponse(code = 200, message = "请求成功"),
    @ApiResponse(code = 400, message = "请求参数没填好"),
    @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
}) 
@ResponseBody
@RequestMapping("/list")
public JsonResult list(@RequestParam String userId) {
    ...
        return JsonResult.ok().put("page", pageUtil);
}

6、@ApiModel、@ApiModelProperty

@ApiModel用于描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)。

@ApiModelProperty用来描述一个Model的属性。

@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{

    @ApiModelProperty(value = "是否成功",required=true)
    private boolean success=true;   

    @ApiModelProperty(value = "错误码")
    private Integer errCode;

    @ApiModelProperty(value = "提示信息")
    private String message;

    @ApiModelProperty(value = "数据")
    private Object data;

    /* getter/setter 略*/
}

7、 @PathVariable

@PathVariable用于获取get请求url路径上的参数,即参数绑定的作用,通俗的说是url中”?“前面绑定的参数。

@GetMapping("/query/{id}")
private List<Student> queryById( @ApiParam(name = "id", value = "学生id", required = true) @PathVariable("id") Long id) {
    List<Student> studentList = studentService.queryById(id);
    return studentList;
}

8、 @RequestParam

@RequestParam用于获取前端传过来的参数,可以是getpost请求,通俗的说是url中”?”后面拼接的每个参数。

@GetMapping("/query/student")
private List<Student> queryByIdStu( @ApiParam(name = "byId", value = "学生id", required = false) @RequestParam("id") Long id) {
    List<Student> studentList = studentService.queryById(id);
    return studentList;
}

参考

《Java 集成 Swagger 组件》有2条评论

  1. 可以直接 pom 文件引用

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

    参考链接:https://blog.csdn.net/m0_64371025/article/details/122934021

发表评论