SpringBoot使用Swagger2实现Restful AP
2018-04-09 本文已影响619人
dalaoyang
很多时候,我们需要创建一个接口项目用来数据调转,其中不包含任何业务逻辑,比如我们公司。这时我们就需要实现一个具有Restful API的接口项目。
本文介绍springboot使用swagger2实现Restful API。
本项目使用mysql+jpa+swagger2。
首先pom中加入swagger2,代码如下:
<?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.dalaoyang</groupId>
<artifactId>springboot_swagger2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_swagger2</name>
<description>springboot_swagger2</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
接下来是配置文件,和整合jpa一样。代码如下:
##端口号
server.port=8888
##数据库配置
##数据库地址
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##数据库用户名
spring.datasource.username=root
##数据库密码
spring.datasource.password=root
##数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
创建一个swagger2配置类,简单解释一下,@Configuration注解让spring来加载配置,@EnableSwagger2开启swagger2。
package com.dalaoyang.config;
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 dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.config
* @email yangyang@dalaoyang.cn
* @date 2018/4/9
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.dalaoyang.swagger"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("使用Swagger2构建RESTful APIs")
.description("关注博主博客:https://www.dalaoyang.cn/")
.termsOfServiceUrl("https://www.dalaoyang.cn/")
.contact("dalaoyang")
.version("1.0")
.build();
}
}
创建一个user类作为model
package com.dalaoyang.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.model
* @email yangyang@dalaoyang.cn
* @date 2018/4/9
*/
@Entity
@ApiModel(description = "user")
public class User {
@ApiModelProperty(value = "主键id",hidden = true)
@GeneratedValue
@Id
int id;
@ApiModelProperty(value = "用户名称")
@NotNull
@Column
String userName;
@ApiModelProperty(value = "用户密码")
@Column
String userPassword;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public User(int id, String userName, String userPassword) {
this.id=id;
this.userName = userName;
this.userPassword = userPassword;
}
public User(String userName, String userPassword) {
this.userName = userName;
this.userPassword = userPassword;
}
public User() {
}
}
jpa数据操作类UserRepository
package com.dalaoyang.repository;
import com.dalaoyang.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.repository
* @email yangyang@dalaoyang.cn
* @date 2018/4/9
*/
public interface UserRepository extends JpaRepository<User,Integer> {
User findById(int id);
}
然后添加文档内容,其实和写controller一样,只不过方法和参数中间穿插一些注解。
package com.dalaoyang.swagger;
import com.dalaoyang.model.User;
import com.dalaoyang.repository.UserRepository;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.swagger
* @email yangyang@dalaoyang.cn
* @date 2018/4/9
*/
@RestController
@RequestMapping(value="/users")
@Api(value="用户操作接口",tags={"用户操作接口"})
public class UserSwagger {
@Autowired
UserRepository userRepository;
@ApiOperation(value="获取用户详细信息", notes="根据用户的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true,paramType = "query", dataType = "Integer")
@GetMapping(value="/findById")
public User findById(@RequestParam(value = "id")int id){
User user = userRepository.findById(id);
return user;
}
@ApiOperation(value="获取用户列表", notes="获取用户列表")
@GetMapping(value="/getUserList")
public List getUserList(){
return userRepository.findAll();
}
@ApiOperation(value="保存用户", notes="保存用户")
@PostMapping(value="/saveUser")
public String saveUser(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){
userRepository.save(user);
return "success!";
}
@ApiOperation(value="修改用户", notes="修改用户")
@ApiImplicitParams({
@ApiImplicitParam(name="id",value="主键id",required=true,paramType="query",dataType="Integer"),
@ApiImplicitParam(name="username",value="用户名称",required=true,paramType="query",dataType = "String"),
@ApiImplicitParam(name="password",value="用户密码",required=true,paramType="query",dataType = "String")
})
@GetMapping(value="/updateUser")
public String updateUser(@RequestParam(value = "id")int id,@RequestParam(value = "username")String username,
@RequestParam(value = "password")String password){
User user = new User(id, username, password);
userRepository.save(user);
return "success!";
}
@ApiOperation(value="删除用户", notes="根据用户的id来删除用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true,paramType = "query", dataType = "Integer")
@DeleteMapping(value="/deleteUserById")
public String deleteUserById(@RequestParam(value = "id")int id){
User user = userRepository.findById(id);
userRepository.delete(user);
return "success!";
}
}
启动项目,访问http://localhost:8888/swagger-ui.html,可以看到如下图
image为了方便大家学习观看,我分别用了几种不同的方法写,
1.删除用户,代码如下
@ApiOperation(value="删除用户", notes="根据用户的id来删除用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true,paramType = "query", dataType = "Integer")
@DeleteMapping(value="/deleteUserById")
public String deleteUserById(@RequestParam(value = "id")int id){
User user = userRepository.findById(id);
userRepository.delete(user);
return "success!";
}
image
2.获取用户详细信息
@ApiOperation(value="获取用户详细信息", notes="根据用户的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true,paramType = "query", dataType = "Integer")
@GetMapping(value="/findById")
public User findById(@RequestParam(value = "id")int id){
User user = userRepository.findById(id);
return user;
}
image
3.获取用户列表
@ApiOperation(value="获取用户列表", notes="获取用户列表")
@GetMapping(value="/getUserList")
public List getUserList(){
return userRepository.findAll();
}
image
4.保存用户
@ApiOperation(value="保存用户", notes="保存用户")
@PostMapping(value="/saveUser")
public String saveUser(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){
userRepository.save(user);
return "success!";
}
image
5.修改用户
@ApiOperation(value="修改用户", notes="修改用户")
@ApiImplicitParams({
@ApiImplicitParam(name="id",value="主键id",required=true,paramType="query",dataType="Integer"),
@ApiImplicitParam(name="username",value="用户名称",required=true,paramType="query",dataType = "String"),
@ApiImplicitParam(name="password",value="用户密码",required=true,paramType="query",dataType = "String")
})
@PutMapping(value="/updateUser")
public String updateUser(@RequestParam(value = "id")int id,@RequestParam(value = "username")String username,
@RequestParam(value = "password")String password){
User user = new User(id, username, password);
userRepository.save(user);
return "success!";
}
image
然后给大家分享一下我之前学习时记录在有道云笔记的关于swagger2的使用说明,原创作者是谁,我也记不清了。如果原创作者看到的话,可以私聊我,我给您的名字加上,抱歉。
@Api:用在请求的类上,表示对类的说明
tags="说明该类的作用,可以在UI界面上看到的注解"
value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
示例:
@Api(tags="APP用户注册Controller")
@ApiOperation:用在请求的方法上,说明方法的用途、作用
value="说明方法的用途、作用"
notes="方法的备注说明"
示例:
@ApiOperation(value="用户注册",notes="手机号、密码都是必输项,年龄随边填,但必须是数字")
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(不常用)
· form(不常用)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值
示例:
@ApiImplicitParams({
@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
@ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})
@ApiResponses:用在请求的方法上,表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiOperation(value = "select1请求",notes = "多个参数,多种的查询参数类型")
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@ApiModel:用于响应类上,表示一个返回响应数据的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景,
请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:用在属性上,描述响应类的属性
示例:
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{
@ApiModelProperty(value = "是否成功")
private boolean success=true;
@ApiModelProperty(value = "返回对象")
private Object data;
@ApiModelProperty(value = "错误编号")
private Integer errCode;
@ApiModelProperty(value = "错误信息")
private String message;
}
POST请求传入对象
示例:
@ApiOperation(value="保存用户", notes="保存用户")
@RequestMapping(value="/saveUser", method= RequestMethod.POST)
public String saveUser(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){
userDao.save(user);
return "success!";
}
源码下载 :大老杨码云
个人网站:https://dalaoyang.cn