springboot搭建Swagger api文档的测试demo

Swagger官网地址:https://swagger.io

Swagger是一款rest api文档生成工具。

Swagger可以生成一个具有互动性的API控制台,开发者可以快速学习和尝试API

可以生成客户端SDK代码用于各种不同的平台上的的实现

Swagger文件可以在许多不同的平台上从代码注释中自动生成

 

本demo记录springboot集成Swagger2的使用步骤。

1、首先创建一一个springboot项目,项目中 引用Swagger依赖包

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

 

在启动类的统计包下创建Swagger的配置类

package com.swagger;

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

/**
 * @author dayu
 * @create 2019/3/12 10:39
 * @Description 配置类或者在类上添加扫描包的位置注解
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //指定扫描的包
                .apis(RequestHandlerSelectors.basePackage("com.swagger.controller"))
                //.apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 创建api基本信息,会显示在页面文档中
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("dayu swagger2 test")
                .description("更多请关注:https://www.xxx.site")
                .license("官网地址")
                .licenseUrl("https://www.xxx.site")
                .contact("大宇")
                .version("1.1")
                .build();
    }
}

 

三:添加文档类容

上述的配置已经可以生产文档了,但是默认的配置文档都是函数名本身,对测试或者开发者来说并不太友好,所有需要对每个方法添加一些说明来解释具体步骤或者功能

Swagger使用的注解说明:

  1.   @Api 用在类上,说明类的作用
  2.   @ApiOperation 在方法上,里面有方法说明
  3.   @ApiImplicitParams 用在方法上,由多组@ApiImplicitParam参数说明组成
  4.        @ApiImplicitParam 用在方法上,说明方法中的一个参数说明
  5.        @ApiResponses 用于表示一组响应
  6.        @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息,code:数字,如400,message:信息,如“请求参数没填好”,response:抛出异常的类
  7.        @ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
  8.        @ApiModelProperty:描述一个model的属性

注意:@ApiImplicitParam的参数说明:

paramType:指定参数放在哪个地方

header:请求参数放置于Request Header,使用@RequestHeader获取

query:请求参数放置于请求地址,使用@RequestParam获取

path:(用于restful接口)-->请求参数的获取:@PathVariable

body:(不常用)

form(不常用)

name:参数名

 

dataType:参数类型

 

required:参数是否必须传

true | false

value:说明参数的意思

 

defaultValue:参数的默认值

 

demo:

package com.swagger.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
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.RestController;

import javax.websocket.server.PathParam;

/**
 * @author dayu
 * @Description 注意@ApiImplicitParam的使用会影响程序运行,如果使用不当可能造成控制器收不到消息
 */
@RestController
@RequestMapping("/hello")
@Api(value = "测试swagger的controller")
public class HelloController {
    
    @RequestMapping(value = "say", method = RequestMethod.GET)
    @ApiOperation(value = "说你好方法", notes = "输入就可以说hello")
    public String say() {
        System.out.println("HelloController.say");
        return "HelloController.say hello swagger2.0";
    }

    @RequestMapping(value = "saytoSome", method = RequestMethod.GET)
    @ApiOperation(value = "needParam", notes = "添加参数")
    @ApiImplicitParam(paramType = "query", value = "姓名", name = "name", required = true, dataType = "String")
    public String saytoSome(@PathParam(value = "name") String name) {
        if (StringUtils.isEmpty(name)) {
            return "无人区";
        }
        if (name.equals("xiaoming")) {
            return "是个好人";
        } else {
            return "hello " + name;
        }
    }

    @RequestMapping(value = "bye", method = RequestMethod.POST)
    @ApiOperation(value = "说goodBye方法", notes = "输入就可以说再见")
    public String bye() {
        System.out.println("HelloController.byebye");
        return "byebye swagger2.0";
    }

    @ApiOperation(value = "updatePwd",notes = "更改密码")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query",name = "userId",value = "用户名",required = true,dataType = "Integer"),
        @ApiImplicitParam(paramType = "query",name = "password",value = "旧密码",required = true,dataType = "String"),
        @ApiImplicitParam(paramType = "query",name = "newPassword",value = "新密码",required = true,dataType = "String"),
    })
    @RequestMapping(value = "updatePwd", method = RequestMethod.POST)
    public String updatePwd(Integer userId, String password, String newPassword) {
        if(userId<=0 ||userId>5){
            return "用户id错误";
        }

        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)) {
            return "密码不能为空";
        }

        if (password.equals(newPassword)) {
            return "密码不能相同!";
        }
        return "密码修改成功!";
    }
}

 

四: 启动项目,直接方法swagger-ui的页面即可进入主页

地址:http://localhost:8080/swagger-ui.html

需要注意的两点:

  1、 @ApiImplicitParam中的属性paramType会直接影响程序的运行期,如果paramType与方法参数获取使用的注解不一致,会直接影响到参数的接收。

  2、Conntroller中定义的方法必须在@RequestMapper中显示的指定RequestMethod类型,否则SawggerUi会默认为全类型皆可访问, API列表中会生成多条项目。

 Swagger UI面板说明:

 

五、测试接收对象的参数

注意: 在后台采用对象接收参数时,Swagger自带的工具采用的是JSON传参,测试时需要在参数上加入@RequestBody,正常运行采用form或URL提交时候请删除。

 对象类上需要添加api注解

package com.swagger.pojo;

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

@ApiModel(value = "人物模型")
public class User {
    @ApiModelProperty(name = "userId", value = "人物id", required = true)
    private Integer userId;
    @ApiModelProperty(value = "人物姓名", required = true)
    private String name;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

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

    public User() {
    }

    public User(Integer userId, String name) {
        this.userId = userId;
        this.name = name;
    }

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

 

 controller测试demo

 

package com.swagger.controller;

import com.swagger.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试使用
 */
@RestController
@RequestMapping("/user")
@Api(value = "人物信息接口模拟")
public class UserController {


    @PostMapping("addUser")
    @ApiOperation(value = "添加用户", notes = "添加用户信息")
    public String addUser(@RequestBody User user) {
        if (null == user || user.getUserId() == null) {
            return "添加失败,参数错误!";
        }

        return "添加成功!" + user.toString();
    }

    @DeleteMapping("deleteUser/{userId}")
    @ApiOperation(value = "删除用户", notes = "删除用户信息")
    @ApiImplicitParam(paramType = "query", value = "用户id", name = "userId", required = true, dataType = "Integer")
    public String deleteUser(@RequestParam Integer userId) {
        if (userId <= 0) {
            return "删除失败";
        }
        return "删除成功!" + userId;
    }

    @PostMapping("updateUser/{userId}")
    @ApiOperation(value = "修改用户", notes = "修改用户信息")
    @ApiImplicitParam(paramType = "query", value = "用户id", name = "userId", required = true, dataType = "Integer")
    public String updateUser(@RequestParam Integer userId, @RequestBody User user) {
        if (userId <= 0 || userId > 8) {
            return "修改失败";
        }
        return "修改成功!" + user.toString();
    }

    @GetMapping("findUser/{userId}")
    @ApiOperation(value = "select用户", notes = "select用户信息")
    @ApiImplicitParam(paramType = "query", value = "用户id", name = "userId", required = true, dataType = "Integer")
    public String findUser(@RequestParam int userId) {
        List<User> list = new ArrayList<>();
        list.add(new User(1, "aaa"));
        list.add(new User(2, "bbb"));
        list.add(new User(3, "ccc"));
        for (User user : list) {
            if (user.getUserId() == userId) {
                return "查找到用户!" + user.toString();
            }
        }
        return "查找失败";
    }
}

 

请求查看api

以上代码参考csdn作者:https://blog.csdn.net/sanyaoxu_2/article/details/80555328

posted @ 2019-03-12 16:10  大宇007  阅读(566)  评论(0编辑  收藏  举报