springboot整合swagger2

什么是Swagger2

編寫和維護(hù)接口文檔是每個(gè)程序員的職責(zé),根據(jù) Swagger2 可以快速幫助我們編寫最新的API接口文檔,再也不用擔(dān)心開會(huì)前仍忙于整理各種資料了,間接提升了團(tuán)隊(duì)開發(fā)的溝通效率。常用注解swagger通過注解表明該接口會(huì)生成文檔,包括接口名、請(qǐng)求方法、參數(shù)、返回信息的等等。

配置
  • 首先需要在pom.xml添加Swagger2所需要的依賴。
 <!--swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
  • 添加Swagger2的配置文件 config -->SwaggerConfig.java
    1.添加@EnableSwagger2


    @EnableSwagger2.png

    2.配置創(chuàng)建文檔API信息


    文檔api信息.png
  • 注意:此處的params為header中的token令牌,并非所有的請(qǐng)求都需要token參數(shù)。
    3.配置Info信息

    info.png

    效果:


    配置信息后的效果.png

    4.關(guān)于http請(qǐng)求狀態(tài)碼信息的配置


    請(qǐng)求狀態(tài)碼信息.png

    效果:
    狀態(tài)碼.png
package com.wsy.mybatis_plus_demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        //================== 需要的參數(shù)START========================
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder token = new ParameterBuilder();
        token.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(token.build());
        //  ==================== 需要的參數(shù) END ====================
        return new Docket(DocumentationType.SWAGGER_2)
                .globalOperationParameters(pars)//全局非必填參數(shù)
                .globalResponseMessage(RequestMethod.GET,customerResponseMessage())
                .globalResponseMessage(RequestMethod.GET,customerResponseMessage())
                .apiInfo(apiInfo())
                .select()
                //項(xiàng)目包所在的controller
                .apis(RequestHandlerSelectors.basePackage("com.wsy.mybatis_plus_demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("零食商販--基礎(chǔ)數(shù)據(jù)API說明文檔")
                .description("2019-07-20 開始項(xiàng)目")
                .contact(new Contact("shine_rainbow","http://github.com/shinefairy","804886201@qq.com"))
                //.termsOfServiceUrl("localhost:8080/")
                .version("1.0")
                .build();
    }
    private List<ResponseMessage> customerResponseMessage(){
        List<ResponseMessage> list = new ArrayList<>();
        list.add(new ResponseMessageBuilder().code(200).message("請(qǐng)求成功").build());
        list.add(new ResponseMessageBuilder().code(201).message("資源創(chuàng)建成功").build());
        list.add(new ResponseMessageBuilder().code(204).message("服務(wù)器成功處理了請(qǐng)求,但不需要返回任何實(shí)體內(nèi)容").build());
        list.add(new ResponseMessageBuilder().code(400).message("請(qǐng)求失敗,具體查看返回業(yè)務(wù)狀態(tài)碼與對(duì)應(yīng)消息").build());
        list.add(new ResponseMessageBuilder().code(401).message("請(qǐng)求失敗,未經(jīng)過身份認(rèn)證").build());
        list.add(new ResponseMessageBuilder().code(405).message("請(qǐng)求方法不支持").build());
        list.add(new ResponseMessageBuilder().code(415).message("請(qǐng)求媒體類型不支持").build());
        list.add(new ResponseMessageBuilder().code(500).message("服務(wù)器遇到了一個(gè)未曾預(yù)料的狀況,導(dǎo)致了它無法完成對(duì)請(qǐng)求的處理").build());
        list.add(new ResponseMessageBuilder().code(503).message("服務(wù)器當(dāng)前無法處理請(qǐng)求,這個(gè)狀況是臨時(shí)的,并且將在一段時(shí)間以后恢復(fù)").build());
        return list;
    }
}

  • Controller中添加相關(guān)注解
    1.添加@Api注解在Controller


    @Api.png
    • @Api:用在請(qǐng)求的類上,說明該類的作用

@Api:用在請(qǐng)求的類上,說明該類的作用
tags="說明該類的作用"
value="該參數(shù)沒什么意義,所以不需要配置"

參數(shù)說明

注解 參數(shù) 參數(shù)說明
@api tags 說明該類的作用,可以在UI界面上看到的注解
@api value 該參數(shù)沒什么意義,在UI界面上也看到,所以不需要配置

實(shí)例:@Api(tags="APP用戶注冊(cè)Controller")

2.添加@ApiOperation等注解在請(qǐng)求方法上


添加注解在請(qǐng)求方法上.png
  • @ApiOperation:用在請(qǐng)求的方法上,說明方法的作用

@ApiOperation:"用在請(qǐng)求的方法上,說明方法的作用"
value="說明方法的作用"
notes="方法的備注說明"

參數(shù)說明

注解 參數(shù) 參數(shù)說明
@api value 說明方法的作用
@api notes 方法的備注說明

實(shí)例:@ApiOperation(value="用戶注冊(cè)",notes="手機(jī)號(hào)、密碼都是必輸項(xiàng),年齡隨邊填,但必須是數(shù)字")

  • @ApiImplicitParams:用在請(qǐng)求的方法上,包含一組參數(shù)說明

@ApiImplicitParams:用在請(qǐng)求的方法上,包含一組參數(shù)說明
@ApiImplicitParam:用在 @ApiImplicitParams 注解中,指定一個(gè)請(qǐng)求參數(shù)的配置信息
name:參數(shù)名
value:參數(shù)的漢字說明、解釋
required:參數(shù)是否必須傳
paramType:參數(shù)放在哪個(gè)地方
· header --> 請(qǐng)求參數(shù)的獲?。篅RequestHeader
· query --> 請(qǐng)求參數(shù)的獲取:@RequestParam
· path(用于restful接口)--> 請(qǐng)求參數(shù)的獲?。篅PathVariable
· body(不常用)
· form(不常用)
dataType:參數(shù)類型,默認(rèn)String,其它值dataType="Integer"
defaultValue:參數(shù)的默認(rèn)值

示例:

@ApiImplicitParams({
    @ApiImplicitParam(name="mobile",value="手機(jī)號(hào)",required=true,paramType="form"),
    @ApiImplicitParam(name="password",value="密碼",required=true,paramType="form"),
    @ApiImplicitParam(name="age",value="年齡",required=true,paramType="form",dataType="Integer")
})
  • @ApiResponses:用于請(qǐng)求的方法上,表示一組響應(yīng)

@ApiResponses:用于請(qǐng)求的方法上,表示一組響應(yīng)
@ApiResponse:用在@ApiResponses中,一般用于表達(dá)一個(gè)錯(cuò)誤的響應(yīng)信息
code:數(shù)字,例如400
message:信息,例如"請(qǐng)求參數(shù)沒填好"
response:拋出異常的類

@ApiOperation(value = "select1請(qǐng)求",notes = "多個(gè)參數(shù),多種的查詢參數(shù)類型")
@ApiResponses({
    @ApiResponse(code=400,message="請(qǐng)求參數(shù)沒填好"),
    @ApiResponse(code=404,message="請(qǐng)求路徑?jīng)]有或頁(yè)面跳轉(zhuǎn)路徑不對(duì)")
})
  • @ApiModel:用于響應(yīng)類上,表示一個(gè)返回響應(yīng)數(shù)據(jù)的信息

@ApiModel:用于響應(yīng)類上,表示一個(gè)返回響應(yīng)數(shù)據(jù)的信息
(這種一般用在post創(chuàng)建的時(shí)候,使用@RequestBody這樣的場(chǎng)景,
請(qǐng)求參數(shù)無法使用@ApiImplicitParam注解進(jìn)行描述的時(shí)候)
@ApiModelProperty:用在屬性上,描述響應(yīng)類的屬性

示例:

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

@ApiModel(description= "返回響應(yīng)數(shù)據(jù)")
public class RestMessage implements Serializable{

    @ApiModelProperty(value = "是否成功")
    private boolean success=true;
    @ApiModelProperty(value = "返回對(duì)象")
    private Object data;
    @ApiModelProperty(value = "錯(cuò)誤編號(hào)")
    private Integer errCode;
    @ApiModelProperty(value = "錯(cuò)誤信息")
    private String message;

    /* getter/setter */
}
package com.wsy.mybatis_plus_demo.controller;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wsy.mybatis_plus_demo.entity.User;
import com.wsy.mybatis_plus_demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shine
 * @since 2019-07-19
 */
@Api(tags = "用戶接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 根據(jù)id查找用戶
     */
    @ApiOperation(value = "獲取用戶詳細(xì)信息",notes = "根據(jù)url傳來的id獲取用戶對(duì)象")
    @ApiImplicitParam(name = "id",value = "用戶id",required = true,dataType = "Integer",paramType = "path")
    @GetMapping(value = "/{id}")
    public User getUserById(@PathVariable(value = "id") Integer id){
        User user = userService.getById(id);
        return ObjectUtils.isNotEmpty(user)?user:null;
    }
}


效果:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前后端分離后,維護(hù)接口文檔基本上是必不可少的工作。一個(gè)理想的狀態(tài)是設(shè)計(jì)好后,接口文檔發(fā)給前端和后端,大伙按照既定的...
    java云帆閱讀 838評(píng)論 0 1
  • swagger2是一款幫助我們生成restful接口細(xì)節(jié)記錄信息的工具。 引入Swagger2 創(chuàng)建配置類 App...
    策馬踏清風(fēng)閱讀 201評(píng)論 0 1
  • 1、引入依賴 2、啟動(dòng)類加上注解 3、創(chuàng)建swagger2的工具類 4、在controller上用注解解釋各個(gè)方法...
    閑置的Programmer閱讀 252評(píng)論 0 0
  • 在一座小鎮(zhèn)上,有一個(gè)漂亮的姑娘名叫佳雯,佳雯喜歡吹口琴,她吹出來的聲音清脆悅耳,能夠吸引到各種小貓小狗之類的...
    6bc1e64eb65f閱讀 235評(píng)論 0 1
  • 今天是個(gè)紀(jì)念的日子,昨天單位開會(huì),聽到一個(gè)同事講到她工作的方式方法,我瞬間有些驚呆??傄詾樵谖覀冞@種單位是沒有人會(huì)...
    幸福樹的枝丫閱讀 188評(píng)論 0 0

友情鏈接更多精彩內(nèi)容