SpringBoot使用Swagger2實(shí)現(xiàn)Restful API

很多時候该窗,我們需要創(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翻擒,可以看到如下圖

swagger

github地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末氓涣,一起剝皮案震驚了整個濱河市牛哺,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌劳吠,老刑警劉巖引润,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異痒玩,居然都是意外死亡淳附,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門蠢古,熙熙樓的掌柜王于貴愁眉苦臉地迎上來奴曙,“玉大人,你說我怎么就攤上這事草讶∏⒃悖” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵堕战,是天一觀的道長坤溃。 經(jīng)常有香客問我,道長嘱丢,這世上最難降的妖魔是什么薪介? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮越驻,結(jié)果婚禮上汁政,老公的妹妹穿的比我還像新娘。我一直安慰自己缀旁,他們只是感情好记劈,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著诵棵,像睡著了一般抠蚣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上履澳,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天嘶窄,我揣著相機(jī)與錄音,去河邊找鬼距贷。 笑死柄冲,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的忠蝗。 我是一名探鬼主播现横,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了戒祠?” 一聲冷哼從身側(cè)響起骇两,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎姜盈,沒想到半個月后低千,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡馏颂,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年示血,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片救拉。...
    茶點(diǎn)故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡难审,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出亿絮,到底是詐尸還是另有隱情告喊,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布壹无,位于F島的核電站葱绒,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏斗锭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一失球、第九天 我趴在偏房一處隱蔽的房頂上張望岖是。 院中可真熱鬧,春花似錦实苞、人聲如沸豺撑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽聪轿。三九已至,卻和暖如春猾浦,著一層夾襖步出監(jiān)牢的瞬間陆错,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工金赦, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留音瓷,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓夹抗,卻偏偏與公主長得像绳慎,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容