Spring Boot (21) 使用Swagger2构建restful API
使用swagger可以与spring mvc程序配合组织出强大的restful api文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入现实代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外swagger2也提供了强大的也卖弄测试功能来调试每个restful API。
首先搭建一个简单的restful api:
User.java
package com.example.bean;
public class User {
private Integer id;
private String name;
private Integer age;
public User() {
}
public User(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
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;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
UserController.java
package com.example.controller; import com.example.bean.User;
import com.example.dao.UserDao;
import org.springframework.web.bind.annotation.*; import javax.annotation.Resource;
import java.util.*; @RequestMapping("/users")
@RestController
public class UserController { @Resource
private UserDao dao; @GetMapping("/")
public List<User> getUserList() {
return dao.getAll();
} @PostMapping("/")
public String postUser(@RequestBody User user) {
dao.addUser(user);
return "success";
} @GetMapping("/{id}")
public User getUser(@PathVariable("id") Integer id) {
return dao.getUserById(id);
} @PutMapping("/{id}")
public String putUser(@PathVariable("id") Integer id, @RequestBody User user) {
user.setId(id);
dao.updateUser(user);
return "success";
} @DeleteMapping("/{id}")
public String deleteUser(@PathVariable("id") Integer id) {
dao.deleteUser(id);
return "success";
} }
UserDao.java
package com.example.dao; import com.example.bean.User;
import org.apache.ibatis.annotations.*; import java.util.List; @Mapper
public interface UserDao {
@Select("select * from user")
List<User> getAll(); @Select("select * from user where id = #{id}")
User getUserById(Integer id); @Insert("insert into user (name,age) values (#{name},#{age})")
int addUser(User user); @Delete("delete from user where id = #{id}")
int deleteUser(Integer id); @Update("update user set name=#{name},age=#{age} where id = #{id}")
int updateUser(User user);
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>demo</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 引入mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!--mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/david2018_db?characterEncoding=utf8
username: root
password: 1234
测试页面:
<html>
<head>
<title>Title</title>
<script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnAdd").click(function(){
var data = {
name:'david',
age:24
};
$.ajax({
url:'/users/',
type:"post",
data:JSON.stringify(data),
contentType:'application/json;charset=UTF-8',
dataType:"json",
success:function(data){
console.log(data)
}
});
});
$("#btnSearchAll").click(function () {
$.ajax({
url:'/users/',
type:'get',
contentType:'application/json;charset=UTF-8',
dataType:"json",
success:function(data){
console.log(data)
}
})
}) });
</script>
</head>
<body>
<button id="btnAdd">添加</button>
<button id="btnSearchAll">查询</button>
</body>
</html>
功能如下:
| 请求类型 | URL | 功能说明 |
|---|---|---|
| GET | /users | 查询用户列表 |
| POST | /users | 创建一个用户 |
| GET | /users/id | 根据id查询一个用户 |
| PUT | /users/id | 根据id更新一个用户 |
| DELETE | /users/id | 根据id删除一个用户 |
下面来添加Swagger2依赖
<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>
创建Swagger2配置类
在application.java同级创建Swagger2的配置类Swagger2.java
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("标题")
.description("详细描述")
.termsOfServiceUrl("http://www.david.com")
.contact("david")
.version("1.0")
.build();
}
}
@Configuration注解:让spring来加载该类配置。
@EnableSwagger2注解:启用Swagger2.
createRestApi函数创建Docket的Bean滞后,apiInfo()用来创建该Api的基本信息(这些基本信息会展示在文档页面中)。
select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例扫描指定的Controller,会扫描所有Controller定义的API,并产生文档(除了被@ApiIgnore指定的请求)。
在controller中填写文档的详细描述: UserController.java
package com.example.controller; import com.example.bean.User;
import com.example.dao.UserDao;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*; import javax.annotation.Resource;
import java.util.*; @RequestMapping("/users")
@RestController
public class UserController { @Resource
private UserDao dao; @GetMapping("/")
@ApiOperation(value="获取用户列表",notes = "")
public List<User> getUserList() {
return dao.getAll();
} @PostMapping("/")
@ApiOperation(value = "创建用户",notes = "根据user对象创建用户")
@ApiImplicitParam(name="user",value="用户详细实体",required = true,dataType = "User")
public String postUser(@RequestBody User user) {
dao.addUser(user);
return "success";
} @GetMapping("/{id}")
@ApiOperation(value = "获取用户详细信息",notes = "根据url中的id来获取用户信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer")
public User getUser(@PathVariable("id") Integer id) {
return dao.getUserById(id);
} @PutMapping("/{id}")
@ApiOperation(value="更新用户信息",notes = "根据url的id来查找信息,并根据传入的user修改信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
})
public String putUser(@PathVariable("id") Integer id, @RequestBody User user) {
user.setId(id);
dao.updateUser(user);
return "success";
} @DeleteMapping("/{id}")
@ApiOperation(value="删除用户信息",notes = "根据url中的id来删除用户信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer")
public String deleteUser(@PathVariable("id") Integer id) {
dao.deleteUser(id);
return "success";
} }
启动spring boot程序,在浏览器输入:http://localhost:8080/swager-ui.html 就能看到restful API的页面,可以点开具体的API请求进行操作。

Spring Boot (21) 使用Swagger2构建restful API的更多相关文章
- Spring Boot中使用Swagger2构建RESTful API文档
在开发rest api的时候,为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份RESTful API文档来记录所有接口细节,然而这样的做法有以下几个问题: 1.由于接口众多,并且细 ...
- Spring Boot中使用Swagger2构建RESTful APIs
关于 Swagger Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因: Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API. S ...
- Spring Boot中使用Swagger2构建RESTful APIs介绍
1.添加相关依赖 <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <depen ...
- Spring Boot中使用Swagger2生成RESTful API文档(转)
效果如下图所示: 添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <!-- https://mvnrepository.com/artifact/io.springfox ...
- Spring MVC中使用 Swagger2 构建Restful API
1.Spring MVC配置文件中的配置 [java] view plain copy <!-- 设置使用注解的类所在的jar包,只加载controller类 --> <contex ...
- springboot集成swagger2构建RESTful API文档
在开发过程中,有时候我们需要不停的测试接口,自测,或者交由测试测试接口,我们需要构建一个文档,都是单独写,太麻烦了,现在使用springboot集成swagger2来构建RESTful API文档,可 ...
- Spring Boot中使用Swagger2构建强大的RESTful API文档
由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这 ...
- Spring Boot 中使用 Swagger2 构建强大的 RESTful API 文档
项目现状:由于前后端分离,没有很好的前后端合作工具. 由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型.HTTP头部信息.HTTP请求内容等),高质量地创建这份文档本身就是件非常吃力的事,下 ...
- Spring Boot 入门系列(二十二)使用Swagger2构建 RESTful API文档
前面介绍了如何Spring Boot 快速打造Restful API 接口,也介绍了如何优雅的实现 Api 版本控制,不清楚的可以看我之前的文章:https://www.cnblogs.com/zha ...
随机推荐
- kvm virt-install 使用小结
简介: virt-install 能够为KVM.Xen或其它支持libvrit API的hypervisor创建虚拟机并完成GuestOS安装. 此外,它能够基于串行控制台.VNC或SDL支持文本或图 ...
- 通过javascript在iframe中加载html
在spring mvc中,虽然有时候,在控制器中设置返回值是json对象,但在拦截器出现错误的时候,仍然可能返回html(根据设置的不同),如果要展示这些html,最好把他们放入iframe中,以防这 ...
- ES6学习历程(变量的声明)
2019-01-25: 一:变量的声明: 1.对于变量的声明添加了let,const两种方式 关于let: (1)不存在变量提升--必须先声明再使用; (2)会出现暂时性死区--在一个方法外用var声 ...
- 1.4.1 安装Python扩展库
Python之所以得到各行业领域工程师.策划师以及管理人员的青睐,与涉及各行业各领域开发的扩展库也有很大关系,不仅数量众多.功能强大,关键是用起来很方便.虽然Python标准库已经拥有了非常强大的功能 ...
- 1、ceph-deploy之部署ceph集群
环境说明 server:3台虚拟机,挂载卷/dev/vdb 10G 系统:centos7.2 ceph版本:luminous repo: 公网-http://download.ceph.com,htt ...
- 洛谷 P1843 奶牛晒衣服
题目背景 熊大妈决定给每个牛宝宝都穿上可爱的婴儿装 . 于是 , 为牛宝宝洗晒衣服就成了很不爽的事情. 题目描述 熊大妈请你帮助完成这个重任 . 洗完衣服后 , 你就要弄干衣服 . 衣服在自然条件下用 ...
- Macbook上安装Win7经验总结
昨天兴致突发,想在Macbook上装个win7跑双系统玩玩,结果遇到了几个非常奇葩的问题.折腾了差不多一天,硬盘分区又合并分区N次,若干次卡死,最后总算搞定.记录下经验,以慰后来人. 问题一:安装程序 ...
- BZOJ1443 游戏game (二分图染色+匈牙利算法)
先对整幅图进行二分图染色,再跑一遍匈牙利算法.如果最大匹配数=点数*2,那么输出WIN. 对于任何一个非必须在最大匹配上的点,即为所求的点. Program Test375num2; type arr ...
- 【ACM】hdu_zs3_1007_Rails_201308100802
Rails Time Limit : 2000/1000ms (Java/Other) Memory Limit : 20000/10000K (Java/Other)Total Submissi ...
- iOS:去除UITableView的空白行
要去除UITableView在运行时显示的多余空白行,只需要将TableView的Style从Plain改为Grouped即可.