在上个项目StringBoot-mybatis基础上加入Swagger2
想看StringBoot整合mybatis的,可以看我上篇博客
https://blog.csdn.net/qq_28655127/article/details/94431926
手写Api文档的几个痛点:
- 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
- 接口返回结果不明确
- 不能直接在线测试接口,通常需要使用工具,比如postman
- 接口文档太多,不好管理
Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。
其他的不多说,想要了解Swagger的,可以去Swagger官网,可以直接使用Swagger editor编写接口文档,当然我们这里讲解的是SpringBoot整合Swagger2,直接生成接口文档的方式。
1.加入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2.Swagger配置类
用@Configuration注解该类,等价于XML中配置beans;用@Bean标注方法等价于XML中配置bean。
package com.bootmy;
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;
/**
* swagger2 配置类
* Created by ruglcc on 2018/8/6.
*/
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.bootmy.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("更多Spring Boot相关文章请关注:https://blog.csdn.net/tangcv/article/category/7771327")
.termsOfServiceUrl("https://blog.csdn.net/tangcv/article/details/81455100")
.contact("壹陣上古風")
.version("1.0")
.build();
}
}
3.启动类上加上注解@EnableSwagger2 表示开启Swagger
package com.bootmy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@MapperScan(value = "com.bootmy.mapper")
@ComponentScan(basePackages = "com.bootmy")
@EnableSwagger2
public class SpringBootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisApplication.class, args);
}
}
4.创建一个config包名,加入Json格式输出类 JsonResult
package com.bootmy.config;
public class JsonResult {
private String status = null;
private Object result = null;
// Getter Setter
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
5.返回类ResultInfo
/**
* Copyright © 2018pactera. All rights reserved.
*
* @Title: ResultInfo.java
* @Prject: management_system-gm
* @Package: com.pactera.pmo.utils
* @Description: TODO
* @author: P0114720
* @date: 2018年3月13日 下午2:26:09
* @version: V1.0
*/
package com.bootmy.config;
import java.io.Serializable;
/**
* @ClassName: ResultInfo
* @Description: TODO
* @author: P0114720
* @date: 2018年3月13日 下午2:26:09
*/
public class ResultInfo implements Serializable{
/**
* @fieldName: serialVersionUID
* @fieldType: long
* @Description: TODO
*/
private static final long serialVersionUID = 1L;
public enum CODE { // code 枚举
// 添加枚举的指定常量
SUCCESS(0), //成功
FAILURE(1), //失败
RQUEST_SUCCESS(10000); //请求成功
// 必须增加一个构造函数,变量,得到该变量的值
private int code = 0;
private CODE(int code) {
this.code = code;
}
/**
* @return 枚举变量实际返回值
*/
public int getCode() {
return code;
}
}
private int code;
private String message;
private Object data;
public ResultInfo() {
super();
}
public ResultInfo(int code) {
this.code = code;
}
public ResultInfo(int code, String message) {
this.code = code;
this.message = message;
}
public ResultInfo(int code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* @return the code
*/
public int getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(int code) {
this.code = code;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the data
*/
public Object getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(Object data) {
this.data = data;
}
}
6.新建一个Controller,名字为 DictController
package com.bootmy.controller;
import com.bootmy.Service.DictService;
import com.bootmy.config.JsonResult;
import com.bootmy.mapper.DictMapper;
import com.bootmy.model.Dict;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import java.util.*;
@RequestMapping("/Dict")
@Controller
public class DictController {
@Resource
public DictService dictService;
@Resource
public DictMapper dictMapper;
/**
* 根据ID查询对应的数据字典
* @param id
* @return
*/
@ApiOperation(value="获取数据字典详细信息", notes="根据url的id来获取数据字典详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
@RequestMapping(value = "find/{id}", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
JsonResult r = new JsonResult();
try {
Dict dict = dictService.findUserById(Long.valueOf(id));
r.setResult(dict);
r.setStatus("成功");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("异常");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 查询数据字典列表
* @return
*/
@ApiOperation(value="获取数据字典列表", notes="获取数组字典列表")
@RequestMapping(value = "findAll", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserList (){
JsonResult r = new JsonResult();
try {
List<Dict> dictList = dictService.findAllUser();
r.setResult(dictList);
r.setStatus("成功");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("异常");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 添加数据字典
* @return
*/
@ApiOperation(value="创建数据字典", notes="根据Dict对象创建数据字典")
@ApiImplicitParam(name = "dict", value = "数据字典详细实体Dict", required = true, dataType = "Dict")
@RequestMapping(value = "dict", method = RequestMethod.POST)
public ResponseEntity<JsonResult> add (@RequestBody Dict dict){
JsonResult r = new JsonResult();
try {
dictMapper.insert(dict);
r.setResult(dict.getId());
r.setStatus("成功");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("异常");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 根据id删除对应的数据字典
* @param id
* @return
*/
@ApiOperation(value="删除数据字典", notes="根据url的id来指定删除数据字典")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
@RequestMapping(value = "deleteById/{id}", method = RequestMethod.DELETE)
public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){
JsonResult r = new JsonResult();
try {
dictMapper.deleteByPrimaryKey(Long.valueOf(id));
r.setResult(id);
r.setStatus("成功");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("异常");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 根据id修改数据字典信息
* @param dict
* @return
*/
@ApiOperation(value="更新", notes="根据url的id来指定更新数据字典")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "字典ID", required = true, dataType = "Long",paramType = "path"),
@ApiImplicitParam(name = "dict", value = "用户实体dict", required = true, dataType = "Dict")
})
@RequestMapping(value = "update/{id}", method = RequestMethod.PUT)
public ResponseEntity<JsonResult> update (@PathVariable("id") Long id, @RequestBody Dict dict){
JsonResult r = new JsonResult();
try {
Dict d = new Dict();
d.setId(id);
d.setDictName(dict.getDictName());
d.setDictCode(dict.getDictCode());
d.setDictStatus(dict.getDictStatus());
dictMapper.updateByPrimaryKeySelective(d);
r.setResult(d);
r.setStatus("成功");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("失败");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
@ApiIgnore//使用该注解忽略这个API
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String jsonTest() {
return " hi you!";
}
}
7.application.properties文件中设置过文件访问权限的地方, spring.mvc.static-path-pattern=/static/** 加上注释,端口由于8080端口被Jenkins 占用,改成了8079,具体
server.port=8079
#设定ftl文件路径
spring.freemarker.template-loader-path=classpath:/templates
spring.freemarker.cache=false
spring.freemarker.suffix=.html
#设定静态文件路径,js,css等
#spring.mvc.static-path-pattern=/static/**
#热部署生效
spring.devtools.restart.enabled:true
#设置重启的目录
spring.devtools.restart.additional-paths:src/main/java
#classpath目录下的WEB-INF文件夹内容修改不重启
spring.devtools.restart.exclude:WEB-INF/**
#端口后加
#server.servlet.context-path=/caisexiaochou
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/bootmy?characterEncoding=UTF-8&useUnicode=true
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.minIdle=3
spring.datasource.maxWait=600000
spring.datasource.removeAbandoned=true
spring.datasource.removeAbandonedTimeout=180
spring.datasource.timeBetweenEvictionRunsMillis=600000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=50
spring.datasource.filters=stat
mybatis.mapper-locations=classpath*:mapping/*Mapper.xml
#mybatis.type-aliases-package=com.bootMy.model.*
#pagehelper分页插件
pagehelper.helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
启动项目,访问http://127.0.0.1:8079/swagger-ui.html
下面的是从简书上看到的,可能以后用得到
swagger常用注解说明
常用到的注解有:
- Api
- ApiModel
- ApiModelProperty
- ApiOperation
- ApiParam
- ApiResponse
- ApiResponses
- ResponseHeader
1.api标记
Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:
@Api(value = "/user", description = "Operations about user")
与Controller注解并列使用。 属性配置:
属性名称 | 备注 |
---|---|
value | url的路径值 |
tags | 如果设置这个值、value的值会被覆盖 |
description | 对api资源的描述 |
basePath | 基本路径可以不配置 |
position | 如果配置多个Api 想改变显示的顺序位置 |
produces | For example, “application/json, application/xml” |
consumes | For example, “application/json, application/xml” |
protocols | Possible values: http, https, ws, wss. |
authorizations | 高级特性认证时配置 |
hidden | 配置为true 将在文档中隐藏 |
在SpringMvc中的配置如下:
@Controller
@RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
@Api(value = "/pet", description = "Operations about pets")
public class PetController {
}
- ApiOperation标记
ApiOperation:用在方法上,说明方法的作用,每一个url资源的定义,使用方式:
@ApiOperation(
value = "Find purchase order by ID",
notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
response = Order,
tags = {"Pet Store"})
与Controller中的方法并列使用。
属性配置:
属性名称 | 备注 |
---|---|
value | url的路径值 |
tags | 如果设置这个值、value的值会被覆盖 |
description | 对api资源的描述 |
basePath | 基本路径可以不配置 |
position | 如果配置多个Api 想改变显示的顺序位置 |
produces | For example, “application/json, application/xml” |
consumes | For example, “application/json, application/xml” |
protocols | Possible values: http, https, ws, wss. |
authorizations | 高级特性认证时配置 |
hidden | 配置为true 将在文档中隐藏 |
response | 返回的对象 |
responseContainer | 这些对象是有效的 “List”, “Set” or “Map”.,其他无效 |
httpMethod | “GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH” |
code | http的状态码 默认 200 |
extensions | 扩展属性 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order/{orderId}", method = GET)
@ApiOperation(
value = "Find purchase order by ID",
notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
response = Order.class,
tags = { "Pet Store" })
public ResponseEntity<Order> getOrderById(@PathVariable("orderId") String orderId)
throws NotFoundException {
Order order = storeData.get(Long.valueOf(orderId));
if (null != order) {
return ok(order);
} else {
throw new NotFoundException(404, "Order not found");
}
}
- ApiParam标记
ApiParam请求属性,使用方式:
public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true) User user)
与Controller中的方法并列使用。
属性配置:
属性名称 | 备注 |
---|---|
name | 属性名称 |
value | 属性值 |
defaultValue | 默认属性值 |
allowableValues | 可以不配置 |
required | 是否属性必填 |
access | 不过多描述 |
allowMultiple | 默认为false |
hidden | 隐藏该属性 |
example | 举例子 |
在SpringMvc中的配置如下:
public ResponseEntity<Order> getOrderById(
@ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true)
@PathVariable("orderId") String orderId)
- ApiResponse
ApiResponse:响应配置,使用方式:
@ApiResponse(code = 400, message = "Invalid user supplied")
与Controller中的方法并列使用。 属性配置:
属性名称 备注 | |
---|---|
code | http的状态码 |
message | 描述 |
response | 默认响应类 Void |
reference | 参考ApiOperation中配置 |
responseHeaders | 参考 ResponseHeader 属性配置说明 |
responseContainer | 参考ApiOperation中配置 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order", method = POST)
@ApiOperation(value = "Place an order for a pet", response = Order.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
public ResponseEntity<String> placeOrder(
@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
storeData.add(order);
return ok("");
}
- ApiResponses
ApiResponses:响应集配置,使用方式:
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
与Controller中的方法并列使用。 属性配置:
属性名称 备注 | |
---|---|
value | 多个ApiResponse配置 |
在SpringMvc中的配置如下:
@RequestMapping(value = "/order", method = POST)
@ApiOperation(value = "Place an order for a pet", response = Order.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
public ResponseEntity<String> placeOrder(
@ApiParam(value = "order placed for purchasing the pet", required = true) Order order) {
storeData.add(order);
return ok("");
}
- ResponseHeader
响应头设置,使用方法
@ResponseHeader(name="head1",description="response head conf")
与Controller中的方法并列使用。 属性配置:
属性名称 备注 | |
---|---|
name | 响应头名称 |
description | 头描述 |
response | 默认响应类 Void |
responseContainer | 参考ApiOperation中配置 |
在SpringMvc中的配置如下:
@ApiModel(description = "群组")
- 其他
- @ApiImplicitParams:用在方法上包含一组参数说明;
- @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
- paramType:参数放在哪个地方
- name:参数代表的含义 value:参数名称
- dataType:参数类型,有String/int,无用
- required : 是否必要
- defaultValue:参数的默认值
- @ApiResponses:用于表示一组响应;
- @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息;
- code: 响应码(int型),可自定义
- message:状态码对应的响应信息
- @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候;
- @ApiModelProperty:描述一个model的属性。