一、swagger介绍:
- API文档的规范且完整框架。
- 提供描述、生产、消费和可视化RESTful Web Service。
- 是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面
二、使用方法
效果:
方法:
1、在pom.xml文件中添加第三方swagger依赖
<!-- 版本 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger2.version>2.9.2</swagger2.version>
<swagger2.ui.version>2.9.2</swagger2.ui.version>
<swagger2.bootstrap.ui.version>1.9.6</swagger2.bootstrap.ui.version>
<swagger2.annotations.version>1.5.22</swagger2.annotations.version>
<swagger2.models.version>1.5.22</swagger2.models.version>
</properties>
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.ui.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>${swagger2.bootstrap.ui.version}</version>
</dependency>
<!-- 防止swagger-ui.html页面触发1.5.20的警告 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger2.annotations.version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger2.models.version}</version>
</dependency>
二、swagger的configuration
注意的是swagger scan base package,这是扫描注解的配置,即你的API接口位置
package com.xu.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
private static final String splitor = ";";//分包分隔符
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(basePackage("com.xu"))//多包用分隔符分割
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("测试配置 API")
.description("API文档").version("1.0").build();
}
/**
* 重写basePackage方法,实现扫描多个包的功能
* @param basePackage
* @return
*/
public static Predicate<RequestHandler> basePackage(final String basePackage) {
return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
}
private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
return input -> {
// 循环判断匹配
for (String strPackage : basePackage.split(splitor)) {
boolean isMatch = input.getPackage().getName().startsWith(strPackage);
if (isMatch) {
return true;
}
}
return false;
};
}
@SuppressWarnings("deprecation")
private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
return Optional.fromNullable(input.declaringClass());
}
}
用法
package com.lyht.manager.system.controller;
import com.aliyuncs.exceptions.ClientException;
import com.lyht.annotation.PhoneNumber;
import com.lyht.http.LyhtHttpResponse;
import com.lyht.http.response.LyhtResponseBody;
import com.lyht.manager.log.annotation.OptLog;
import com.lyht.manager.log.constant.OptLogModuleConstant;
import com.lyht.manager.log.constant.OptLogTypeConstant;
import com.lyht.manager.system.service.SysUserService;
import com.lyht.manager.system.service.impl.AuthServiceImpl;
import com.lyht.manager.system.vo.LoginByPhoneVO;
import com.lyht.manager.system.vo.PasswordModifyByAccountIdVO;
import com.lyht.manager.system.vo.PasswordModifyByAccountVO;
import com.lyht.manager.system.vo.LoginByPasswordVO;
import com.lyht.manager.system.vo.PasswordModifyByPhoneVO;
import com.lyht.manager.system.vo.PasswordModifyByUserVO;
import com.lyht.manager.system.vo.RegisterByAccountVO;
import com.lyht.manager.system.vo.RegisterByPhoneVO;
import com.lyht.manager.system.vo.RegisterByUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
/**
* 登录/注册 API
*
* @author NING MEI
*
*/
@Api(value = "/auth", tags = "登录/注册 API")
@RestController
@RequestMapping("/auth")
@Validated
public class AuthController {
@Resource
private AuthServiceImpl loginService;
@Resource
private SysUserService sysUserService;
@ApiOperation(value = "发送登录短信验证码", notes = "发送登录短信验证码")
@ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query")
@OptLog(value = "发送登录短信验证码", module = OptLogModuleConstant.AUTH, type = OptLogTypeConstant.SEND_MSG)
@GetMapping("/send/login/phone/code")
public LyhtResponseBody<Boolean> sendLoginCode(@NotBlank(message = "手机号不能为空!") @PhoneNumber String phone)
throws ClientException {
boolean sendLoginCode = loginService.sendLoginCode(phone);
return LyhtHttpResponse.success(sendLoginCode);
}
@ApiOperation(value = "发送修改密码短信验证码", notes = "发送修改密码短信验证码")
@ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query")
@OptLog(value = "发送修改密码短信验证码", module = OptLogModuleConstant.AUTH, type = OptLogTypeConstant.SEND_MSG)
@GetMapping("/send/modify/phone/code")
public LyhtResponseBody<Boolean> sendModifyPasswordCode(@NotBlank(message = "手机号不能为空!") @PhoneNumber String phone)
throws ClientException {
boolean sendModifyPasswordCode = loginService.sendModifyPasswordCode(phone);
return LyhtHttpResponse.success(sendModifyPasswordCode);
}
}
四、API常用方法
1、Api
@Api()用于类;表示标识这个类是swagger的资源
tags–表示说明
value–也是说明,可以使用tags替代
2、ApiOperation
@ApiOperation() 用于方法;表示一个http请求的操作
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)
3、ApiParam
@ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填
示例:
@Api(value="用户controller",tags={"用户操作接口"})
@RestController
public class UserController {
@ApiOperation(value="获取用户信息",tags={"获取用户信息copy"},notes="注意问题点")
@GetMapping("/getUserInfo")
public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username) {
// userService可忽略,是业务逻辑
User user = userService.getUserInfo();
return user;
}
}
4、ApiModel
@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
5、ApiModelProperty
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
示例:
@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@ApiModelProperty(value="用户名",name="username",example="xingguo")
private String username;
@ApiModelProperty(value="状态",name="state",required=true)
private Integer state;
private String password;
private String nickName;
private Integer isDeleted;
@ApiModelProperty(value="id数组",hidden=true)
private String[] ids;
private List<String> idList;
//省略get/set
}