1. 程式人生 > >SpringBoot整合Swagger生成介面文件

SpringBoot整合Swagger生成介面文件

一、簡介

Swagger是一個功能強大的API框架,它支援線上文件的檢視以及線上文件的測試,方便我們前後端開發人員對接。Swagger使用起來也很簡單,只需要加入swagger對應的依賴以及在controller類以及方法中加入相應的註解說明,swagger就會幫我們自動生成API介面文件。

本文主要通過一個簡單的模擬增刪查改功能實現springboot整合swagger2生成Restful 介面文件。

二、新建springboot_swagger專案

【a】swagger依賴:

<!--Swagger2依賴-->
<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>

具體pom.xml:

<?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.springboot.wsh</groupId>
	<artifactId>springboot_swagger</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot_swagger</name>
	<description>使用Swagger生成API文件</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.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-web</artifactId>
		</dependency>

		<!--Swagger2依賴-->
		<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>

【b】新建User實體類

package com.springboot.wsh.entity;

import java.io.Serializable;

/**
 * @Title: User
 * @ProjectName springboot_swagger
 * @Description: 使用者實體類
 * @Author WeiShiHuai
 * @Date 2018/9/29 17:58
 */
public class User implements Serializable {

    private Long id;
    private String username;
    private String password;

    public User(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

【c】新建SwaggerConfiguration配置類

在配置類上加上註解@EnableSwagger2、@Configuration,主要配置一些apiInfo資訊(標題、描述、版本號等)以及配置Docket(文件型別、api資訊、生成介面文件需要掃描的包等)

@EnableSwagger2:開啟swagger功能

package com.springboot.wsh.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;

/**
 * @Title: SwaggerConfiguration
 * @ProjectName springboot_swagger
 * @Description: Swagger配置類
 * @Author WeiShiHuai
 * @Date 2018/9/29 17:36
 * <p>
 * 說明: Swagger2可以幫助我們快速生成API介面文件,方便我們進行除錯。只需要在對應的Controller方法上加上一些註解即可,
 * 訪問地址: http://主機名稱:埠號/swagger-ui.html  ( 如:http://localhost:8080/swagger-ui.html)
 */
//@Configuration表示這是一個配置類
@Configuration
//@EnableSwagger2: 開啟Swagger2生成api文件功能
@EnableSwagger2
public class SwaggerConfiguration {

    /**
     * 配置api資訊(標題、描述、版本號等)
     *
     * @return api資訊
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("使用Swagger2生成API介面文件")   //標題
                .description("swagger2提供了強大的介面文件功能,方便介面除錯")  //描述資訊
                .version("1.0")   //版本號
                .termsOfServiceUrl("https://blog.csdn.net/Weixiaohuai")  //服務URL地址
                .build();
    }

    /**
     * 配置Docket物件,配置一些資訊(文件型別、api資訊、生成介面文件需要掃描的包等)
     *
     * @return Docket物件
     */
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)  //指定文件型別
                .apiInfo(apiInfo()) //指定Api相關資訊
                .select()  //選擇那些路徑和api會生成文件
                .apis(RequestHandlerSelectors.basePackage("com.springboot.wsh.controller"))  //指定生成文件掃描的包
                .paths(PathSelectors.any())  //指定對所有路徑進行監控
                .build();

    }

}

【d】新建UserController

這個類主要部分是swagger2部分,增刪查改功能只是模擬而已。

package com.springboot.wsh.controller;

import com.springboot.wsh.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

/**
 * @Title: UserController
 * @ProjectName springboot_swagger
 * @Description: 使用者Controller
 * @Author WeiShiHuai
 * @Date 2018/9/29 17:49
 * <p>
 * 說明: Swagger的好處
 * 1. 簡單方便、自動生成文件、除錯方便、方便前後端對接
 * 2. 減少前後臺的研發溝通成本,相對文件化的資源,支援簡單的手工測試
 */
@RestController
@RequestMapping("/user")
//@Api: 標識該Controller的功能
@Api("使用者-相關服務Api")
public class UserController {

    private static List<User> userList = new ArrayList<>();

    static {
        userList.add(new User(1L, "zhangsan", "123456"));
        userList.add(new User(2L, "lisi", "654321"));
    }

    @GetMapping("/getUserList")
    //@ApiOperation: 標識該介面的作用
    @ApiOperation(value = "獲取使用者列表資訊", notes = "獲取使用者列表資訊", httpMethod = "GET")
    public List<User> getUserList() {
        return userList;
    }

    @GetMapping("/getUserInfo/{id}")
    @ApiOperation(value = "根據id獲取使用者資訊", notes = "根據id獲取使用者資訊", httpMethod = "GET")
    //@ApiImplicitParam: 標識介面中引數的型別、是否必填、描述等
    @ApiImplicitParam(name = "id", value = "使用者id", dataType = "Long", paramType = "path", required = true)
    public User getUserInfo(@PathVariable("id") Long id) {
        return userList.get(id.intValue());
    }

    @GetMapping("/getUserById")
    @ApiOperation(value = "根據id獲取使用者資訊2", notes = "根據id獲取使用者資訊2", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "使用者id", dataType = "Long", paramType = "query", required = true)
    public User getUserById(@RequestParam("id") Long id) {
        return userList.get(id.intValue());
    }

    @PostMapping("/saveUser")
    @ApiOperation(value = "儲存使用者資訊", notes = "儲存使用者資訊", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "使用者實體資訊", required = true, paramType = "body", dataType = "User")
    })
    public String saveUser(@RequestBody User user) {
        userList.add(user);
        return "save user success!!";
    }

    @PostMapping("/updateUser/{id}")
    @ApiOperation(value = "更新使用者資訊", notes = "更新使用者資訊", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "使用者id", required = true, paramType = "path", dataType = "Long"),
            @ApiImplicitParam(name = "user", value = "使用者實體資訊", required = true, paramType = "body", dataType = "User")
    })
    public String updateUser(@PathVariable("id") Long id, @RequestBody User user) {
        userList.set(id.intValue(), user);
        return "update user success!!";
    }


    @PostMapping("/deleteUser/{id}")
    @ApiOperation(value = "根據使用者id刪除使用者資訊", notes = "根據使用者id刪除使用者資訊", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "使用者id", required = true, paramType = "path", dataType = "Long")
    })
    public String deleteUser(@PathVariable("id") Long id) {
        userList.remove(id.intValue());
        return "delete user success";
    }

    @ApiOperation(value = "批量刪除使用者資訊", notes = "批量刪除使用者資訊", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "pkids", dataType = "List", required = true, value = "主鍵")
    })
    @PostMapping(value = "/deleteByMulti")
    public String deleteByMulti(@RequestBody List<String> pkids) {
        //批量刪除邏輯
        return "deleteByMulti success";
    }

    //@ApiIgnore: 忽略該介面,不生成該介面對應的文件
    @ApiIgnore
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }

}

【e】一些常用註解說明

 @Api: 標識該Controller的功能

 @ApiOperation: 標識該介面的作用 如:

@ApiOperation(value = "獲取使用者列表資訊", notes = "獲取使用者列表資訊", httpMethod = "GET")

@ApiImplicitParam: 標識介面中引數的型別、是否必填、描述等 如:

@ApiImplicitParam(name = "id", value = "使用者id", dataType = "Long", paramType = "path", required = true)
@ApiImplicitParams:可以配置多個@ApiImplicitParam,如:
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "使用者id", required = true, paramType = "path", dataType = "Long"),
        @ApiImplicitParam(name = "user", value = "使用者實體資訊", required = true, paramType = "body", dataType = "User")
})
@ApiIgnore: 忽略該介面,不生成該介面對應的文件,如
@ApiIgnore
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }

三、啟動專案

如圖可以看到,swagger已經幫我們生成了介面文件。我們可以對這些介面進行簡單的測試。

四、補充說明

@ApiImplicitParam】介面中引數說明:

屬性 取值 說明
paramType 查詢引數型別
path 以地址的形式提交資料, @PathVariable()修飾的引數
query 直接跟引數完成自動對映賦值,@RequestParam()修飾的引數
body 以流的形式提交 僅支援POST,@RequestBody修飾的引數
header 引數在request headers 裡邊提交
form 以form表單的形式提交 僅支援POST
dataType Object 引數的資料型別 
Long
String
List
name 接收引數名
value 接收引數的意義描述
required true 引數是否必填
false

示例:

【a】paramType="path"

@ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "使用者id", required = true, paramType = "path", dataType = "Long")
    })
    public String deleteUser(@PathVariable("id") Long id) {}

【b】paramType="query"

@ApiImplicitParam(name = "id", value = "使用者id", dataType = "Long", paramType = "query", required = true)
    public User getUserById(@RequestParam("id") Long id) {
        }

【c】paramType="body"

 @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "使用者實體資訊", required = true, paramType = "body", dataType = "User")
    })
    public String saveUser(@RequestBody User user) {}

五、總結

至此,springboot整合swagger生成api介面文件已經實現了。在微服務中,各個服務都可以整合swagger,這樣我們就可以測試每一個微服務單元的介面,非常方便。本文是作者對swagger的一些總結,僅供大家參考,一起學習一起進步。