很多时候,我们需要创建一个接口项目用来数据调转,其中不包含任何业务逻辑。这时我们就需要实现一个具有Restful API的接口项目。
本文介绍springboot使用swagger2实现Restful API。
这里使用mysql+jpa+swagger2,所以可以直接操作然后看数据库进行测试。
关于springboot和JPA的整合下篇文章介绍
首先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.ooliuyue</groupId>
<artifactId>springboot_swagger</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_swagger</name>
<description>springboot_swagger</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/>
</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>
appication.properties配置
##端口号
server.port=8888
##数据库配置
##数据库地址
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_test?characterEncoding=utf8&useSSL=false
##数据库用户名
spring.datasource.username=root
##数据库密码
spring.datasource.password=root
##数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
##validate 加载hibernate时,验证创建数据库表结构
##create 每次加载hibernate,重新创建数据库表结构,这就是导致数据库表数据丢失的原因。
##create-drop 加载hibernate时创建,退出是删除表结构
##update 加载hibernate自动更新数据库结构
##validate 启动时验证表的结构,不会创建表
##none 启动时不做任何操作
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
创建一个swagger2配置类,简单解释一下,@Configuration注解让spring来加载配置,@EnableSwagger2开启swagger2。
package com.ooliuyue.springboot_swagger.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;
/**
* @Auther: ly
* @Date: 2018/12/18 09:41
*/
@Configuration //让spring来加载配置
@EnableSwagger2 //开启swagger2
public class Swagger2Config {
@Bean
public Docket creatRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.ooliuyue.springboot_swagger"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("使用Swagger2构建RESTful APIs")
.description("一点寒芒先到,随后枪出如龙")
.contact("ooliuyue")
.version("1.0")
.build();
}
}
实体类User
package com.ooliuyue.springboot_swagger.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.*;
/**
* @Auther: ly
* @Date: 2018/12/17 17:56
*/
@Entity
@Table(name = "User")
@ApiModel(description = "user")
public class User {
public User() {
}
public User(Integer id, String username, int age) {
this.id = id;
this.username = username;
this.age = age;
}
@ApiModelProperty(value = "主键id",hidden = true)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ApiModelProperty(value = "用户名称")
@Column
private String username;
@ApiModelProperty(value = "用户年龄")
@Column
private int age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
jpa数据操作类TestUserDao
package com.ooliuyue.springboot_swagger.dao;
import com.ooliuyue.springboot_swagger.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestUserDao extends JpaRepository<User,Integer> {
}
然后添加文档内容,其实和写controller一样,只不过方法和参数中间穿插一些注解。
package com.ooliuyue.springboot_swagger.controller;
import com.ooliuyue.springboot_swagger.dao.TestUserDao;
import com.ooliuyue.springboot_swagger.entity.User;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @Auther: ly
* @Date: 2018/12/18 10:22
*/
@RestController
@RequestMapping(value = "/user")
@Api(value = "用户操作接口",tags = {"用户操作接口"})
public class UserController {
@Autowired
private TestUserDao testUserDao;
@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 = testUserDao.findOne(id);
return user;
}
@ApiOperation(value="获取用户列表", notes="获取用户列表")
@GetMapping(value="/getUserList")
public List getUserList(){
return testUserDao.findAll();
}
@ApiOperation(value="保存用户", notes="保存用户")
@PostMapping(value="/saveUser")
public String saveUser(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){
testUserDao.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="age",value="用户年龄",required=true,paramType="query",dataType = "Integer")
})
@GetMapping(value="/updateUser")
public String updateUser(@RequestParam(value = "id")int id,@RequestParam(value = "username")String username,
@RequestParam(value = "age")Integer age){
User user = new User(id, username, age);
testUserDao.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 = testUserDao.findOne(id);
testUserDao.delete(user);
return "success!";
}
}
启动项目,访问http://localhost:8888/swagger-ui.html,可以看到如下图
swaggergithub地址
网友评论