转自:https://idig8.com/2018/08/31/xiaochengxujavashizhanswagger2deshiyongyujiekouceshi34/

我们已经开发完了一个用户注册的接口,但是我们并没有测试也不知道里面哪里忽略了,有什么问题,先讲下下swagger2,然后集成到spring boot这个项目中。源码:https://github.com/limingios/wxProgram.git 中的wx-springboot

swagger2

  • 介绍
    >swagger2 是可以构建一个非常强大的,是个非常好用的工具也是个非常好用的插件。
  1. 可以生成文档形式的api并提供给不同的团队
  2. 便于自测,也便于领导查阅任务量。
  3. 无需过多冗余的word文档。保证文档是最新的。
  • 使用方法
    >在spring boot common中pom中引入

<!-- swagger2 配置 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
  • 添加swagger2的配置文件
    >在spring boot api中加入java类

package com.idig8;

import java.util.ArrayList;
import java.util.List; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration
@EnableSwagger2
public class Swagger2 { /**
* @Description:swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
*/
@Bean
public Docket createRestApi() { // 为swagger添加header参数可供输入
ParameterBuilder userTokenHeader = new ParameterBuilder();
ParameterBuilder userIdHeader = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
userTokenHeader.name("headerUserToken").description("userToken")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build();
userIdHeader.name("headerUserId").description("userId")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build();
pars.add(userTokenHeader.build());
pars.add(userIdHeader.build()); return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.idig8.controller"))
.paths(PathSelectors.any()).build()
.globalOperationParameters(pars);
} /**
* @Description: 构建 api文档的信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 设置页面标题
.title("使用swagger2构建小程序后端api接口文档")
// 设置联系人
.contact(new Contact("IT人故事会", "https://idig8.com", "公众号:编程坑太多"))
// 描述
.description("欢迎访问接口文档")
// 定义版本号
.version("1.0").build();
} }
  • 修改原有的controller的修改
package com.idig8.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController; import com.github.pagehelper.util.StringUtil;
import com.idig8.pojo.Users;
import com.idig8.service.UserService;
import com.idig8.utils.JSONResult;
import com.idig8.utils.MD5Utils; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; @RestController
@Api(value="用户注册登录的接口",tags={"注册和登录的controller"})
public class RegistLoginController { @Autowired
private UserService userService; @ApiOperation(value="用户注册",notes="用户注册的接口")
@PostMapping("/regist")
public JSONResult regist(@RequestBody Users user) {
//1.判断用户名和密码不能为空
if(StringUtils.isBlank(user.getUsername())||StringUtils.isBlank(user.getPassword())) {
return JSONResult.errorMsg("用户名或密码不能为空");
} //2.判断用户名是否存在
boolean usernameIsExist = userService.queryUsernameIsExist(user.getUsername());
if(!usernameIsExist) {
user.setNickname(user.getUsername());
try {
user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
} catch (Exception e) { return JSONResult.errorMsg(e.getMessage());
}
user.setFollowCounts(0);
user.setReceiveLikeCounts(0);
user.setFansCounts(0);
userService.saveUser(user);
}else {
return JSONResult.errorMsg("用户名或已经存在,请更换在试试!");
} return JSONResult.ok();
}
}
  • 增加Users属性的限制,那些必填 ,spring-boot pojo项目
package com.idig8.pojo;

import javax.persistence.*;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; @ApiModel(value="用户对象",description="这是用户对象")
public class Users {
@Id
@ApiModelProperty(hidden=true)
private String id; /**
* 用户名
*/
@ApiModelProperty(value="用户名",name="username",example="idig8",required=true)
private String username; /**
* 密码
*/
@ApiModelProperty(value="密码",name="password",example="123456",required=true)
private String password; /**
* 我的头像,如果没有默认给一张
*/
@Column(name = "face_image")
private String faceImage; /**
* 昵称
*/
@ApiModelProperty(hidden=true)
private String nickname; /**
* 我的粉丝数量
*/
@ApiModelProperty(hidden=true)
@Column(name = "fans_counts")
private Integer fansCounts; /**
* 我关注的人总数
*/
@ApiModelProperty(hidden=true)
@Column(name = "follow_counts")
private Integer followCounts; /**
* 我接受到的赞美/收藏 的数量
*/
@ApiModelProperty(hidden=true)
@Column(name = "receive_like_counts")
private Integer receiveLikeCounts; /**
* @return id
*/
public String getId() {
return id;
} /**
* @param id
*/
public void setId(String id) {
this.id = id;
} /**
* 获取用户名
*
* @return username - 用户名
*/
public String getUsername() {
return username;
} /**
* 设置用户名
*
* @param username 用户名
*/
public void setUsername(String username) {
this.username = username;
} /**
* 获取密码
*
* @return password - 密码
*/
public String getPassword() {
return password;
} /**
* 设置密码
*
* @param password 密码
*/
public void setPassword(String password) {
this.password = password;
} /**
* 获取我的头像,如果没有默认给一张
*
* @return face_image - 我的头像,如果没有默认给一张
*/
public String getFaceImage() {
return faceImage;
} /**
* 设置我的头像,如果没有默认给一张
*
* @param faceImage 我的头像,如果没有默认给一张
*/
public void setFaceImage(String faceImage) {
this.faceImage = faceImage;
} /**
* 获取昵称
*
* @return nickname - 昵称
*/
public String getNickname() {
return nickname;
} /**
* 设置昵称
*
* @param nickname 昵称
*/
public void setNickname(String nickname) {
this.nickname = nickname;
} /**
* 获取我的粉丝数量
*
* @return fans_counts - 我的粉丝数量
*/
public Integer getFansCounts() {
return fansCounts;
} /**
* 设置我的粉丝数量
*
* @param fansCounts 我的粉丝数量
*/
public void setFansCounts(Integer fansCounts) {
this.fansCounts = fansCounts;
} /**
* 获取我关注的人总数
*
* @return follow_counts - 我关注的人总数
*/
public Integer getFollowCounts() {
return followCounts;
} /**
* 设置我关注的人总数
*
* @param followCounts 我关注的人总数
*/
public void setFollowCounts(Integer followCounts) {
this.followCounts = followCounts;
} /**
* 获取我接受到的赞美/收藏 的数量
*
* @return receive_like_counts - 我接受到的赞美/收藏 的数量
*/
public Integer getReceiveLikeCounts() {
return receiveLikeCounts;
} /**
* 设置我接受到的赞美/收藏 的数量
*
* @param receiveLikeCounts 我接受到的赞美/收藏 的数量
*/
public void setReceiveLikeCounts(Integer receiveLikeCounts) {
this.receiveLikeCounts = receiveLikeCounts;
}
}

运行项目

  • 报错:没有增加扫描
Action:

Consider defining a bean of type 'com.idig8.mapper.UsersMapper' in your configuration.

增加id自动生成Sid的扫描,在service里面注入了和mapper的扫描

··· java
package com.idig8;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan(basePackages=”com.idig8.mapper”)
@ComponentScan(basePackages= {“com.idig8″,”org.n3r.idworker”})
public class Application {

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

}

···

  • 访问网址http://localhost:8081/swagger-ui.html

点击左边的实例,修改内容,点击try it out!

返回的结果

数据库插入正常

  • 里面的内容设置成空

  • 用户名设置成idig8 在试试接口

PS:到这里swagger2的文档配置和接口配置,包括错误的的接口测试基本都演示完毕了。

「小程序JAVA实战」swagger2的使用与接口测试(34)的更多相关文章

  1. 「小程序JAVA实战」springboot的后台搭建(31)

    转自:https://idig8.com/2018/08/29/xiaochengxujavashizhanspringbootdehoutaidajian31/ 根据下面的图,我们来建立下对应的sp ...

  2. 「小程序JAVA实战」微信小程序简介(一)

    转自:https://idig8.com/2018/08/09/xiaochengxu-chuji-01/ 一直想学习小程序,苦于比较忙,加班比较多没时间,其实这都是理由,很多时候习惯了搬砖,习惯了固 ...

  3. 「小程序JAVA实战」微信小程序工程结构了解(五)

    转自:https://idig8.com/2018/08/09/xiaochengxu-chuji-05/ 微信小程序工程结构 audio,button,canvas,checkbox 都是由4个文件 ...

  4. 「小程序JAVA实战」小程序的springboot后台拦截器(61)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudespringboothoutailanjieqi60/ 之前咱们把 ...

  5. 「小程序JAVA实战」小程序头像图片上传(下)(45)

    转自:https://idig8.com/2018/09/09/xiaochengxujavashizhanxiaochengxutouxiangtupianshangchuan44/ 接下来,我们应 ...

  6. 「小程序JAVA实战」小程序的留言和评价功能(70)

    转自:https://idig8.com/2018/10/28/xiaochengxujavashizhanxiaochengxudeliuyanhepingjiagongneng69/ 目前小程序这 ...

  7. 「小程序JAVA实战」小程序的举报功能开发(68)

    转自:https://idig8.com/2018/09/25/xiaochengxujavashizhanxiaochengxudeweixinapicaidancaozuo66-2/ 通过点击举报 ...

  8. 「小程序JAVA实战」小程序的个人信息作品,收藏,关注(66)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudegerenxinxizuopinshoucangguanzhu65 ...

  9. 「小程序JAVA实战」小程序的关注功能(65)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudeguanzhugongneng64/ 在个人页面,根据发布者个人和 ...

随机推荐

  1. HDU2161

    解题思路:判断素数模板题. #include<cstdio> #include<cstring> #include<algorithm> using namespa ...

  2. iOS设备是否越狱的判断代码

    苹果是非常看重产品的安全性的,所以给用户设计了一套复杂的安全机制.这让喜爱自由,崇尚一切开放的程序员们极度不爽,于是越狱就成了苹果和黑客们反复斗法的场所.总体来说,越狱可以让我们随意安装.共享应用,但 ...

  3. 重温CLR(九) 接口

    对于多继承(multiple inheritance)的概念,许多程序员并不陌生,他是指一个类从两个或多个基类派生的能力.例如,假定TransmitData类的作用是发送数据,ReceiveData类 ...

  4. LeetCode Friend Circles

    原题链接在这里:https://leetcode.com/problems/friend-circles/description/ 题目: There are N students in a clas ...

  5. c++调用fortran程序中遇到的问题

    一.C++动态调用Fortran DLL (1)创建FORTRAN DLL工程,生成forsubs.dll文件供调用. ! forsubs.f90 ! ! FUNCTIONS/SUBROUTINES ...

  6. Android.mk用法详解

    一.Android.mk介绍 Android.mk是Android提供的一种makefile文件,用来指定诸如编译生成so库名.引用的头文件目录.需要编译的.c/.cpp文件和.a静态库文件等.要掌握 ...

  7. Dev-C++ 小问题锦集

    C++ project cann't debug Your project does not have debugging information, do you want to enable deb ...

  8. easyui datagrid 基础方法和事件

    数据表格属性(DataGrid Properties) 属性继承控制面板,以下是数据表格独有的属性. 名称 类型 描述 默认值 columns array 数据表格列配置对象,查看列属性以获取更多细节 ...

  9. atoi函数的实现——面试

    主要考虑,字符串中是否有非法字符,字符串是否有溢出控制 #include<stdio.h> int myatoi(const char *str){ ,ret=,i=; if(str[i] ...

  10. Bash命令查找本机公网IP

    用Bash命令查找本机公网IP wget -qO - http://ipecho.net/plain; echo