Spring Boot集成Swagger指南以及常用注解说明

1 简介

Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。
Swagger的目标是为REST APIs定义一个标准的,与语言无关的的接口,使人和计算机在看不到源码或者不能通过网络流量监测的情况下能发现和理解各种服务的功能。当服务通过Swagger定义,消费者就能与远程的服务互动通过少量的实现逻辑。

1.1 swagger组成

Swagger的基础框架如下:
在这里插入图片描述

1.1.1 Swagger-ui

一个无依赖的HTML、JS和CSS集合,可以为Swagger兼容API动态生成优雅文档

1.1.2 swagger-tool

提供各种与Swagger进行集成和交互的工具。例如模式验证,Swagger 1.2文档转换成Swagger 2.0文档等功能

1.1.3 swagger-core

用于Java/Scala的Swagger实现。

1.1.4 swagger-js

用于Java/Script的Swagger实现

1.1.5 swagger-node-express

Swagger模块,用于node.js的Express web应用框架

1.1.6 swagger-codegen

一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端代码

1.2 Swagger作用

 接口文档在线自动生成
 功能测试
 Swagger可以充当前后端交流的重要桥梁,方便快捷,很实用。
 提供API在线测试功能

2 导入依赖

在Spring Boot中引入swagger,需要在pom.xml文件中引入相应的依赖。

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.5.0</version>
    </dependency>
    <!-- config-ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.5.0</version>
    </dependency>

然后通过Maven import相应的jar包依赖即可完成配置。过程比较简单,不再赘述。

3 演示代码

为了演示swagger的使用,笔者使用IDEA建立了一个Spring Boot项目,在代码中引入了相关的swagger依赖,通过代码演示swagger的使用效果。请在有网的条件下学习该项目,因为需要通过maven下载一些基础的依赖包,这样项目才可以正常的运行。项目整体结构如下:
在这里插入图片描述

3.1 pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>swagger</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!-- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.5.0</version>
        </dependency>

    </dependencies>
</project>

pom文件中比较干净,除了需要的spring-boot外,仅仅引用了阿里巴巴的fastjson包,另外的两个io.springfox则是为使用swagger而导入的依赖。

3.2 config包创建swagger配置类

在使用swagger时,应该首先提供一个Swagger配置类,来阐明swagger的基本配置。在配置类中可以包含该套API的说明,包含作者、简介、版本。在该项目中使用的配置类位于config包下,具体代码如下:

package com.example.swagger.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build();
    }

    /**
     * @description: 创建该API的基本信息
     * @url:
     * @author: Song Quanheng
     * @date: 2019/5/10-19:18
     * * @param null
     * @return:
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("Spring Boot中集成swagger")
                .description("博学之,审问之,慎思之,明辨之,笃行之")
                .termsOfServiceUrl("http://www.baidu.com")
                .contact(new Contact("sqh", "https://blog.csdn.net/lk142500", "wannachan@outlook.com"))
                .version("1.0")
                .build();
    }
}

由于自己在applications.properties文件中设置了运行的端口为8083,因此在运行时,可以通过如下的ip地址访问swagger-ui。

ip:port/ swagger-ui.html

由于自己是独立的一个电脑,因此可以使用localhost或者127.0.0.1作为自己的host。因而可以通过如下的地址访问swagger-ui。

localhost:8083/swagger-ui.html

访问之后可以看到如下的页面:
在这里插入图片描述
可以看到描述API的基本信息。

3.3 model包

在model包中,仅一个bean类,用来进行建模登陆信息,其中包含ip、端口、用户名和密码。并且默认ip不可为空,这可以通过javax.validation.constraints的@NotNull (并结合@RequestBody @Valid LoginInfo loginInfo)@Valid注解来实现。

注意:在该类中使用了@ApiModelProperty和@ApiModel,暂时不用关注这两个注解,只要明白通过这两个注解建立了一个swagger所识别的model即可。

LoginInfo类定义如下:

package com.example.swagger.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * 登陆信息,包括ip,端口,用户名,密码
 *
 * @Owner:
 * @Time: 2019/5/9-16:35
 */
@ApiModel(value = "body", description = "登录请求体")
public class LoginInfo implements Serializable {
    @ApiModelProperty(value = "ip地址", name = "ip", example = "192.168.0.233", required = true)
    @NotNull
    private String ip;

    @ApiModelProperty(value = "端口号", name = "port", example = "8000", required = true)
    private String port;

    @ApiModelProperty(value = "用户名", name = "username", example = "admin", required = true)
    private String username;

    @ApiModelProperty(value = "密码", name = "password", example = "abc12345678", required = true)
    private String password;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

在实际使用过程中,可以通过@RequestBody把用户传输过来的json字符串自动转换为LoginInfo对象。

注意:@ApiModel注解的属性value设置为body

3.4 common包

comon包没有什么特别大的用处,主要用来一些公共的部分。在此包中仅有一个类,CommonReturn用于返回json。

package com.example.swagger.common;


import com.alibaba.fastjson.JSONObject;

/**
 * 返回值相关的常用类
 *
 * @Owner:
 * @Time: 2018/12/7-9:46
 */
public class CommonReturn {
    private static final String SUCCESS = "0";
    private static final String FAILURE = "-1";
    public static final String SUCCESS_MSG ="success";
    public static String httpReturn(String result, String msg, Object data) {
        JSONObject ret = new JSONObject();
        ret.put("code", result);
        ret.put("msg", msg);
        if (null != data) {
            ret.put("data", data);
        }
        return ret.toString();
    }


    public static String httpReturn(String result, String msg) {
        return httpReturn(result, msg, null);
    }


    public static String httpReturnSuccess(String msg) {
        return httpReturn(SUCCESS, msg);
    }

    public static String httpReturnSuccess() {
        return httpReturn(SUCCESS, SUCCESS_MSG);
    }
    public static String httpReturnFailure(String msg) {
        return httpReturn(FAILURE, msg);
    }

    public static String httpReturnSuccess(String msg, Object data) {
        return httpReturn(SUCCESS, msg, data);
    }

    public static String httpReturnSuccess(Object data) {
        return httpReturnSuccess(SUCCESS_MSG, data);
    }
}

3.5 启动类

启动类较为简单,仅仅负责简单的启动项目,不赘述。

package com.example.swagger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 入口类
 *
 * @Owner:
 * @Time: 2019/5/9-14:12
 */
@SpringBootApplication
public class SwaggerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwaggerApplication.class, args);
        System.out.println("SwaggerApplication 已经启动");
    }
}

3.6 resources/applications.properties

server.port=8083

3.7 核心controller Device类

笔者在Device类中建立了三个controller,这三个函数对应三个REST请求,其中两个为POST请求,另外一个为GET请求。HTTP现在一共支持8种请求类型,但GET和POST请求较为常用。其他类型的请求照样模拟即可。
为阐述方便,Device类完整代码如下:

package com.example.swagger.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.swagger.model.LoginInfo;
import com.example.swagger.common.CommonReturn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 设备建模类,负责设备的连接和断开连接
 *
 * @Owner:
 * @Time: 2019/5/9-14:54
 */
@Api("设备建模类型,模拟连接、断开连接、打印功能")
@RestController("/device")
public class Device {

    @ApiOperation(value = "设备连接", notes = "连接设备", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/connect", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String connect(@RequestBody @Valid LoginInfo loginInfo) {
        String ip = loginInfo.getIp();
        String port = loginInfo.getPort();
        String userName = loginInfo.getUsername();
        String password = loginInfo.getPassword();

        return CommonReturn.httpReturnSuccess();
    }

    @ApiOperation(value = "断开连接", notes = "注销", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "ip", value = "设备ip", dataType = "String", required = true,
            paramType = "query",defaultValue = "192.168.1.108", example = "192.168.1.100")
    @PostMapping(value = "/disconnect", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String disconnect(@RequestParam("ip") String ip) {
        if (ip.isEmpty()) {
            return CommonReturn.httpReturnFailure("传入的ip非法");
        }
        return CommonReturn.httpReturnSuccess();
    }

    @ApiOperation(value = "获取在线设备", notes = "返回json", httpMethod = "GET")
    @GetMapping(value = "/getAllDevicesOnLine", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAllDevicesOnLine() {

        JSONArray devices = new JSONArray();
        devices.add("192.168.1.108");
        devices.add("192.168.1.109");
        JSONObject ret = new JSONObject();
        ret.put("devices", devices);
        return CommonReturn.httpReturnSuccess(ret);
    }
}

请关注在Device类上的@Api注解以及每个Controller上的@ApiOperation和@ApiImplicitParam,这些注解的属性决定了在swagger-ui上的界面展示效果。

3.8 测试使用Hello类

Hello类主要是用来进行在服务运行时测试服务正常与否,通过发起一个Http请求,通过查看是否可以得到正确的预期返回来判断服务是否正常工作。因此该类较为简单。仅有一个供调用的get类型请求controller。

package com.example.swagger.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.swagger.common.CommonReturn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * REST测试类
 *
 * @Owner:
 * @Time: 2019/5/9-14:15
 */
@Api(value = "服务测试接口")
@RestController
public class Hello {
    @ApiOperation(value = "hello测试", notes = "使用rest模拟测试服务的状态")
    @GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String hello() {
        JSONObject ret = new JSONObject();
        return CommonReturn.httpReturnSuccess();
    }
}

4 效果阐述

4.1 操作列表阐述

可以看到在代码中一共出现了两个@Api注解,分别置于类Hello和Device类上。另外一共出现了4个@ApiOperation,这四个注解的内容如下所示:

    @ApiOperation(value = "设备连接", notes = "连接设备", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "断开连接", notes = "注销", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "获取在线设备", notes = "返回json", httpMethod = "GET")
    @ApiOperation(value = "hello测试", notes = "使用rest模拟测试服务的状态")

访问swagger-ui界面,可以看到如下的内容:
在这里插入图片描述
其中可以很清晰的看到@ApiOperation中的value属性显示在了每一个操作的最右侧。

4.2 特定操作阐述

在三个操作中,分别对应了三个情况,connect操作笔者使用了@RequestBody注解,把用户传入的application/json参数自动转换成了LoginInfo对象。而disconnect则使用了query参数,即在postman中来建立类似的请求时应该使用如下的方式:
http://host:port/pathUrl?key1=value1&key2=value2
而这在使用swagger-ui页面发起请求时是通过在后端指定参数的类型来实现的。最后对于getAllDevicesOnLine则是对应最简单的Get请求,不赘述。
下面详细的阐述

4.2.1 connect

如上所述,在用户传入的json字符串中由于使用了@RequestBody注解会自动的把字符串转化为对象,LoginInfo为一个@ApiModel注解的类型,swagger会自动把该Model对象以一种json的形式展示在swagger-ui上,方便前后端交互。

/**
 * 设备建模类,负责设备的连接和断开连接
 *
 * @Owner:
 * @Time: 2019/5/9-14:54
 */
@Api(value = "设备建模类型,模拟连接、断开连接、打印功能")
@RestController("/device")
public class Device {

    @ApiOperation(value = "设备连接", notes = "连接设备", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PostMapping(value = "/connect", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String connect(@RequestBody @Valid LoginInfo loginInfo)            {
        String ip = loginInfo.getIp();
        String port = loginInfo.getPort();
        String userName = loginInfo.getUsername();
        String password = loginInfo.getPassword();

        return CommonReturn.httpReturnSuccess();
    }

}

为了方便,可以为每个@ApiModelProperty注解example属性,这样可以方便API的使用者使用规范值。参见model包
在这里插入图片描述

注意:该controller演示了从json字符串到bean的转换,并且可以在swagger-ui页面中Model Schema看到在Model中设置的example值。点击Model标签也可以查看该ApiModel的相应属性字符串、类型以及注释。

4.2.2 disconnect

disconnect请求之所以比较特殊,是因为其中使用了query类型的参数,

http://host:port/pathUrl?key1=value1&key2=value2
这在swagger-ui上如何展示呢?

@Api(value = "设备建模类型,模拟连接、断开连接、打印功能")
@RestController("/device")
public class Device {
……
    @ApiOperation(value = "断开连接", notes = "注销", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "ip", value = "设备ip", dataType = "String", required = true,
            paramType = "query",defaultValue = "192.168.1.108", example = "192.168.1.100")
    @PostMapping(value = "/disconnect", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String disconnect(@RequestParam("ip") String ip) {
        if (ip.isEmpty()) {
            return CommonReturn.httpReturnFailure("传入的ip非法");
        }
        return CommonReturn.httpReturnSuccess();
    }

   }

关键仍然是注解部分

@ApiOperation(value = "断开连接", notes = "注销", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiImplicitParam(name = "ip", value = "设备ip", dataType = "String", required = true,
            paramType = "query",defaultValue = "192.168.1.108", example = "192.168.1.100")
    @PostMapping(value = "/disconnect", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

从上面的注解,@PostMapping为Springframework的注解,而且在撰写controller时已经熟悉不再赘述。@ApiOperation为描述该controller整体的注解,而@ApiImplicitParam为描述某个参数的注解。当只有一个参数需要@ApiImplicitParam时,则可以直接使用@ApiImplicitParam,而倘若有多个参数,则需要@ApiImplicitParams注解来包括多个@ApiImplicitParam。
在这里插入图片描述
倘若有两个query参数,即ip和端口,则对应的代码和注解如下:

@ApiOperation(value = "断开连接", notes = "注销", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ip", value = "设备ip", dataType = "String", required = true,
                paramType = "query",defaultValue = "192.168.1.108", example = "192.168.1.100"),
            @ApiImplicitParam(name = "port", value = "端口", dataType = "String", required = true, 
                paramType = "query",defaultValue = "8000", example = "8000")})
    @PostMapping(value = "/disconnect", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String disconnect(@RequestParam("ip") String ip, @RequestParam("port") String port) {
        if (ip.isEmpty()) {
            return CommonReturn.httpReturnFailure("传入的ip非法");
        }
        return CommonReturn.httpReturnSuccess();
    }

而对应的swagger-ui展示如下所示:
在这里插入图片描述

4.2.3 getAllDevicesOnLine

Device类中的getAllDevicesOnLine函数对应为GET类的REST请求,比较简单,因为GET类请求一般不携带参数

@ApiOperation(value = "获取在线设备", notes = "返回json", httpMethod = "GET")
@GetMapping(value = "/getAllDevicesOnLine", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getAllDevicesOnLine() {

    JSONArray devices = new JSONArray();
    devices.add("192.168.1.108");
    devices.add("192.168.1.109");
    JSONObject ret = new JSONObject();
    ret.put("devices", devices);
    return CommonReturn.httpReturnSuccess(ret);
}

接口在swagger-ui上对应的展示如下所示:
在这里插入图片描述
不需要过多的介绍,不再赘述。

5 Swagger核心注解

核心注解,这也是使用Swagger最关键的地方,了解注解和注解中属性的含义,以及在swagger-ui上的展示,这是熟练使用swagger的核心所在。

5.1 @Api

package io.swagger.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Api {
    String value() default ""; //表示说明

    String[] tags() default {""}; // 也是说明,tags可以有多个值

    /** @deprecated */
    @Deprecated
    String description() default "";

    /** @deprecated */
    @Deprecated
    String basePath() default "";

    /** @deprecated */
    @Deprecated
    int position() default 0;

    String produces() default "";

    String consumes() default "";

    String protocols() default "";

    Authorization[] authorizations() default {@Authorization("")};

    boolean hidden() default false;
}

由@Target可以知道,该注解用于注解类型,表示这个类是swagger的资源。貌似在当前swagger版本中,@Api注解中的属性jun 没有展示在swagger-ui界面。

5.2 @ApiOperation

package io.swagger.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiOperation {
    String value(); //描述操作,直接在swagger-ui每个操作的右上角展示含义

    String notes() default ""; //用于提示内容,Implementation Notes

    String[] tags() default {""};  //可以重新打tag,进行分组。

    Class<?> response() default Void.class;

    String responseContainer() default "";

    String responseReference() default "";

    String httpMethod() default "";//使用全大写,GET、POST,与注解的方法类型一致。

    /** @deprecated */
    @Deprecated
    int position() default 0;

    String nickname() default "";

    String produces() default "";

    String consumes() default "";

    String protocols() default "";

    Authorization[] authorizations() default {@Authorization("")};

    boolean hidden() default false;

    ResponseHeader[] responseHeaders() default {@ResponseHeader(
    name = "",
    response = Void.class
)};

    int code() default 200;

    Extension[] extensions() default {@Extension(
    properties = {@ExtensionProperty(
    name = "",
    value = ""
)}
)};
}

由@Target可以看到该注解用来注解方法

5.3 @ApiImplicitParam和@ApiImplicitParams

package io.swagger.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiImplicitParam {
    String name() default "";// 参数名

    String value() default "";// 参数说明

    String defaultValue() default "";// 参数默认值

    String allowableValues() default "";

    boolean required() default false;是否必须

    String access() default "";

    boolean allowMultiple() default false;

    String dataType() default "";// 参数数据类型

    String paramType() default "";// 参数类型,query,body,path等

    String example() default "";// 举例说明

    Example examples() default @Example({@ExampleProperty(
    mediaType = "",
    value = ""
)});
}

@Target({ElementType.METHOD})表示该注解仅可以作用于方法。较为重要的属性为paramType
参数类型如下所示:

类型作用
path以地址的形式提交参数
query直接跟参数完成自动映射赋值,追加在request url之后,参数成为url的一部分
body以流的形式提交,仅支持POST
header参数在request header里
form以form表单的形式提交,仅支持POST

5.4 @ApiModel和@ApiModelProperty

@ApiModel注解类型定义如下:

package io.swagger.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ApiModel {
    String value() default ""; // 表示对象名

    String description() default ""; // 描述

    Class<?> parent() default Void.class;

    String discriminator() default "";

    Class<?>[] subTypes() default {};

    String reference() default "";
}

每个@ApiModel由多个属性组成,描述每个属性的@ApiModelProperty如下所示:

package io.swagger.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiModelProperty {
    String value() default ""; //字段的含义

    String name() default "";  // 字段名称

    String allowableValues() default "";

    String access() default "";

    String notes() default "";

    String dataType() default "";  // 字段数据类型

    boolean required() default false;    // 是否必填

    int position() default 0;

    boolean hidden() default false;  //是否隐藏

    String example() default ""; // 举例说明

    boolean readOnly() default false;

    String reference() default "";
}

由@Target表明该注解作用于方法或者类中字段上。

5.5 @ApiIgnore

package springfox.documentation.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
public @interface ApiIgnore {
}

@ApiIgnore注解作用域方法,类型和参数上,使用即不被swagger显示在页面上。

6 问题解决

6.1 No enum constant org.springframework.web.bind.annotation.RequestMethod.get

6.1.1 问题描述

java.lang.IllegalArgumentException: No enum constant org.springframework.web.bind.annotation.RequestMethod.get
	at java.lang.Enum.valueOf(Enum.java:238) ~[na:1.8.0_131]
	at org.springframework.web.bind.annotation.RequestMethod.valueOf(RequestMethod.java:35) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
	at springfox.documentation.swagger.readers.operation.OperationHttpMethodReader.apply(OperationHttpMethodReader.java:50) ~[springfox-swagger-common-2.5.0.jar:2.5.0]
	at springfox.documentation.spring.web.plugins.DocumentationPluginsManager.operation(DocumentationPluginsManager.java:113) [springfox-spring-web-2.5.0.jar:2.5.0]
	at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941) [guava-18.0.jar:na]
	at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824) [guava-18.0.jar:na]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
	at com.example.swagger.SwaggerApplication.main(SwaggerApplication.java:15) [classes/:na]

这个问题的出现原因如下:

@ApiOperation(value = "获取在线设备", notes = "返回json", httpMethod = "get")
@GetMapping(value = "/getAllDevicesOnLine", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getAllDevicesOnLine() {

    JSONArray devices = new JSONArray();
    devices.add("192.168.1.108");
    devices.add("192.168.1.109");
    JSONObject ret = new JSONObject();
    ret.put("devices", devices);
    return CommonReturn.httpReturnSuccess(ret);
}

在上述的swagger注解中出现了如下的内容

@ApiOperation(value = “获取在线设备”, notes = “返回json”, httpMethod = “get”)

而swagger提供的类HttpMethod,类型定义如下:

package io.swagger.models;

public enum HttpMethod {
    POST,
    GET,
    PUT,
    PATCH,
    DELETE,
    HEAD,
    OPTIONS;

    private HttpMethod() {
    }
}

可以看到字符串类型为全大写GET,而编写的代码中@ApiOperation(httpMethod = “get”),因此弹出了警告。

6.1.2 问题解决

修改该controller上的@ApiOperation,成如下的内容

@ApiOperation(value = “获取在线设备”, notes = “返回json”, httpMethod = “GET”)
即可消除该警告。

7 引用

Swagger学习及运用(三)–Swagger注解文档及常用参数配置运用
@ApiResponses、@ApiResponse、@ApiImplicitParams、ApiImplicitParam
swagger2 注解说明 ( @ApiImplicitParams )

8 总结

文档主要介绍了Spring Boot与Swagger整合的过程,通过一个小项目演示了swagger-ui在解释REST类API的强大功能,美观、可运行、优雅可以程序员带来美感,大概这就是Swagger受到推崇的一个原因。
在文档中同样也包含了项目的源码分析,以及在swagger使用过程中的关键注解,熟练使用这些swagger注解,这样就能熟练的使用swagger来阐述自己的REST接口。

9下载

源码下载

swagger.zip

文档下载

Spring Boot集成Swagger使用指南.pdf
2019-05-12 11:59:14于杭州市马塍路36号

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值