天天看點

SpringBoot使用Swagger2實作Restful API

很多時候,我們需要建立一個接口項目用來資料調轉,其中不包含任何業務邏輯,比如我們公司。這時我們就需要實作一個具有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 [email protected]
 * @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 [email protected]
 * @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 [email protected]
 * @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 [email protected]
 * @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!";
    }
           

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;
    }
           

3.擷取使用者清單

@ApiOperation(value="擷取使用者清單", notes="擷取使用者清單")
    @GetMapping(value="/getUserList")
    public List getUserList(){
        return userRepository.findAll();
    }
           

4.儲存使用者

@ApiOperation(value="儲存使用者", notes="儲存使用者")
    @PostMapping(value="/saveUser")
    public String saveUser(@RequestBody @ApiParam(name="使用者對象",value="傳入json格式",required=true) User user){
        userRepository.save(user);
        return "success!";
    }
           

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!";
    }
           

然後給大家分享一下我之前學習時記錄在有道雲筆記的關于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