Swagger文档 --

作用:Swagger是一个规范和完整的框架,用于生成,描述,调用和可视化RestFul风格的Web服务,主要用于接口文档的在线自动生成,功能测试。

Maven:

         <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>

配置类:

package com.example.demo.swaggerTest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
//表示用来启动swagger2
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket ProductApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .pathMapping("/")
                .select()
                .build().apiInfo(productApiInfo());
    }

    private ApiInfo productApiInfo() {
// 参数一:大标题,表示当前的文档是那个接口文档
// 参数二:是对当前文档的描述
// 参数三:表示当前的版本
// 参数四:
// 参数五:
// 参数六:
// 参数七:点击参数六的时候回连接到当前地址
        ApiInfo apiInfo = new ApiInfo("XXX系统数据接口文档",
                "文档描述。。。",
                "1.0.0",
                "API TERMS URL",
                "联系人邮箱",
                "license",
                "https://www.baidu.com/");
        return apiInfo;
    }
}

效果:


接口配置 ---  参数传递

package com.example.demo.Controller;

import io.swagger.annotations.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.security.util.Password;

/*
 * 一个用来测试swagger注解的控制器
 * 注意@ApiImplicitParam的使用会影响到程序的运行,如果使用的不当可能造成控制器收不到消息
 * */
@Controller
@RequestMapping("/say")
// 用来对当前的类进行说明
@Api(value = "测试Swagger注解的控制器")
public class SayController {

    @ResponseBody
// 如果不设置method,在显示的时候,会显示七中方式
    @RequestMapping(value = "/getUserName", method = RequestMethod.GET)
//    用来给api增加方法的说明   value 对方法的描述    notes 具体的描述
    @ApiOperation(value = "根据用户编号获取用户姓名", notes = "test :仅1和2有正确的返回")
//    用来给方法中的入参增加说明  该注解在使用的时候需要注意的是paramType属性,用于对方法中的参数进行规范和说明
//    @ApiImplicitParam(paramType = "query", name = "userNumber", value = "用户编号", required = true, dataType = "Integer")
// @ApiParam 跟@ApiImplicitParam 注解的作用是一致的,唯一不同的是没有paramType的指定和dataTyoe的两个参数
    public String getUserName(@RequestParam @ApiParam(value = "用户编号",name = "userNumber" ,required = true ) Integer userNumber) {

        if (userNumber == 1) {
            return "1";
        } else if (userNumber == 2) {
            return "2";
        } else {
            return "未知";
        }
    }

    @RequestMapping(value = "/updatePassword",method = RequestMethod.GET)
    @ResponseBody
//    对接口参数的说明
    @ApiOperation(value = "修改用户密码", notes = "根据用户id修改密码")
// 如果是多个参数,需要分别进行描述,所以需要使用ApiImplicitParams注解来操作
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", value = "用户id", required = true, dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "password", value = "旧密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "newPassword", value = "新密码", required = true, dataType = "String")
    })
    public String updatePassword(@RequestParam(value = "userId") Integer userId, @RequestParam(value = "password") String password
            , @RequestParam(value = "newPassword") String newPassword) {
        if (userId <= 0 || userId > 2) {
            return "未知";
        }
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)) {
            return "密码为空";
        }
        if (password.equals(newPassword)) {
            return "密码不能相同";
        }
        return "密码修改成功";
    }

}

@ApiImplicitParams注解中paramType的属性
paramType        查询参数类型
      path    以地址的形式提交数据
      query    直接跟参数完成自动映射赋值
      body    以流的形式提交 仅支持POST
     header    参数在request headers 里边提交
    form    以form表单的形式提交 仅支持POST
dataType        参数的数据类型 只作为标志说明,并没有实际验证
    Long    
    String    
name        接收参数名
value        接收参数的意义描述
required        参数是否必填
      true    必填
      false    非必填
defaultValue        默认值

基本上都是使用query来进行操作。

接口配置 --- 对象参数的传递

实体类:

package com.example.demo.entity;

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

/**
 * 实例对象  -- 医生
 */
// 对对象的说明
@ApiModel(value = "对象模型") 
public class DemoDoctor {
// 表示对参数的控制,和声明
    @ApiModelProperty(value = "id", required = true,name = "id" ,notes = "医生的id")
    private Integer id;

    @ApiModelProperty(value = "name", required = false)
    private String name;

    @ApiModelProperty(value = "sex", required = false)
    private Integer sex;

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "DemoDoctor{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Controller

package com.example.demo.Controller;

import com.example.demo.entity.DemoDoctor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpStatusCodeException;

/**
 * 医生
 *
 * @author shanggq
 */
@RequestMapping("/api/v1")
@RestController
@Api(value = "医生信息模拟接口")
public class DoctorTestController {
    @ResponseBody
    @RequestMapping(value = "/doctor", method = RequestMethod.POST)
    @ApiOperation(value = "添加医生的接口", notes = "用于添加医生的信息")
//    Swagger默认使用的接收参数的方式是json进行接收数据,所以需要使用 @RequestBody 用于解析json数据
//    @ApiImplicitParam(name = "",paramType = "quert" ,value = "请求的实体" ,required = true ,dataType = "DemoDoctor")
    public String addDoctor(@RequestBody @ApiParam(value = "请求的实体" ,name = "DemoDoctor",required = true) DemoDoctor demoDoctor) {
        if (null == demoDoctor || demoDoctor.getId() == null) {
            throw new RuntimeException("添加医生失败");
        }
        try {
            System.out.println("------》  添加成功" + demoDoctor.getName());
        } catch (Exception e) {
            throw new RuntimeException("添加医生失败");
        }
        return demoDoctor.getId().toString() + ":" + "添加成功";
    }

    @RequestMapping(value = "/deleteDoctor", method = RequestMethod.DELETE)
    @ResponseBody
    @ApiOperation(value = "删除医生的信息", notes = "用于删除医生的信息")
    @ApiImplicitParam(paramType = "query", name = "doctorId", value = "医生的id", required = true, dataType = "Integer")
    public String deleteDoctor(@RequestParam(value = "doctorId") Integer doctorId) {

        if (doctorId > 2) {
            return "删除失败";
        }
        return " 删除成功";
    }
}

在进行数据传递的时候,Swagger传递的参数的json格式的,如果要将json类型的数据放到对象中需要使用@RequstBody进行声明。

在实体类中的属性上面还可以添加以下注解:

@NotNUll(message="不能为空")

@Range(min = 1,max =3,message="用于限制传递的最大值和最小值")

参考链接:https://blog.csdn.net/xupeng874395012/article/details/68946676

                   https://blog.csdn.net/lamp_yang_3533/article/details/80114083

                  https://www.cnblogs.com/softidea/p/6251249.html

猜你喜欢

转载自blog.csdn.net/weixin_38297879/article/details/83583868