很多時候该窗,我們需要創(chuàng)建一個接口項目用來數(shù)據(jù)調(diào)轉(zhuǎn),其中不包含任何業(yè)務(wù)邏輯蚤霞。這時我們就需要實(shí)現(xiàn)一個具有Restful API的接口項目酗失。
本文介紹springboot使用swagger2實(shí)現(xiàn)Restful API。
這里使用mysql+jpa+swagger2昧绣,所以可以直接操作然后看數(shù)據(jù)庫進(jìn)行測試规肴。
關(guān)于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
##數(shù)據(jù)庫配置
##數(shù)據(jù)庫地址
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_test?characterEncoding=utf8&useSSL=false
##數(shù)據(jù)庫用戶名
spring.datasource.username=root
##數(shù)據(jù)庫密碼
spring.datasource.password=root
##數(shù)據(jù)庫驅(qū)動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
##validate 加載hibernate時夜畴,驗(yàn)證創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu)
##create 每次加載hibernate拖刃,重新創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu),這就是導(dǎo)致數(shù)據(jù)庫表數(shù)據(jù)丟失的原因贪绘。
##create-drop 加載hibernate時創(chuàng)建兑牡,退出是刪除表結(jié)構(gòu)
##update 加載hibernate自動更新數(shù)據(jù)庫結(jié)構(gòu)
##validate 啟動時驗(yàn)證表的結(jié)構(gòu),不會創(chuàng)建表
##none 啟動時不做任何操作
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
創(chuàng)建一個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構(gòu)建RESTful APIs")
.description("一點(diǎn)寒芒先到苞也,隨后槍出如龍")
.contact("ooliuyue")
.version("1.0")
.build();
}
}
實(shí)體類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數(shù)據(jù)操作類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> {
}
然后添加文檔內(nèi)容,其實(shí)和寫controller一樣粘秆,只不過方法和參數(shù)中間穿插一些注解如迟。
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="獲取用戶詳細(xì)信息", notes="根據(jù)用戶的id來獲取用戶詳細(xì)信息")
@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="根據(jù)用戶的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翻擒,可以看到如下圖
github地址