天天看點

springboot中使用Swagger2生成接口文檔

  1. 添加swagger2依賴
<!-- swagger2 配置 用于生成接口文檔-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>
           
  1. 建立配置檔案
package com.lyl.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
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;

/**
 * 通路http://localhost/swagger-ui.html 檢視資訊
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    /**
     * @Description:swagger2的配置檔案,這裡可以配置swagger2的一些基本的内容,比如掃描的包等等
     */
    @Bean
    public Docket createRestApi() {

        // 為swagger添加header參數可供輸入
        ParameterBuilder userTokenHeader = new ParameterBuilder();
        ParameterBuilder userIdHeader = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        userTokenHeader.name("headerUserToken").description("userToken")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();
        userIdHeader.name("headerUserId").description("userId")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();
        pars.add(userTokenHeader.build());
        pars.add(userIdHeader.build());

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.lyl.controller"))
                .paths(PathSelectors.any()).build()
                .globalOperationParameters(pars);
    }

    /**
     * @Description: 建構 api文檔的資訊
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 設定頁面标題
                .title("使用swagger2建構短視訊後端api接口文檔")
                // 設定聯系人
                .contact(new Contact("lyl_藍永龍", "http://www.lyl.com", "[email protected]"))
                // 描述
                .description("歡迎通路短視訊接口文檔,這裡是描述資訊")
                // 定義版本号
                .version("1.0").build();
    }
}

           

這裡有幾個細節

首先添加這兩個注解

springboot中使用Swagger2生成接口文檔

然後在這個方法配置你controller所在的類

springboot中使用Swagger2生成接口文檔

再然後在這裡可以設定接口文檔的基本資訊

springboot中使用Swagger2生成接口文檔

3. 使用方法

在controller類上添加注解

package com.lyl.controller;

import com.lyl.pojo.Users;
import com.lyl.service.UserService;
import com.lyl.utils.IMoocJSONResult;
import com.lyl.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用Api注解來使用swagger2生成接口文檔
 */
@RestController
@Api(value = "使用者注冊登入接口",tags = {"注冊和登入controller"})
public class RegistLoginController {

    @Autowired
    private UserService userService;

    /**
     * 隻不過RequestBody 接收的是請求體裡面的資料;而RequestParam接收的是key-value裡面的參數
     * 注冊接口
     *
     * @ApiOperation(value = "使用者注冊",notes = "使用者注冊接口")
     * 除了要加這個注解還要去實體類加注解
     * @return
     */
    @PostMapping("/regist")
    @ApiOperation(value = "使用者注冊",notes = "使用者注冊接口")
    public JSONResult regist(@RequestBody Users users) throws Exception{
        //1.判斷使用者名和密碼是否為空  這個方法判斷null 和""
        if(StringUtils.isEmpty(users.getUsername())||StringUtils.isEmpty(users.getPassword())){
            return JSONResult.errorMsg("使用者名和密碼不能為空");
        }
        //2.判斷使用者名是否存在
        boolean bool=userService.queryUsernameIsExist(users.getUsername());

        //3.儲存使用者注冊資訊
        if(!bool){
            //使用者名不存在可以注冊
            users.setNickname(users.getUsername());
            users.setPassword(MD5Utils.getMD5Str(users.getPassword()));
            users.setFansCounts(0);
            users.setReceiveLikeCounts(0);
            users.setFollowCounts(0);
            //System.out.println("controller:我運作了嗎");
            userService.saveUser(users);
        }else{
            return JSONResult.errorMsg("使用者名已存在,請換一個試試");
        }
        return JSONResult.ok(users);
    }


           

添加在controller類上 并且設定資訊

@Api(value = “使用者注冊登入接口”,tags = {“注冊和登入controller”})

添加在方法上 設定資訊

@ApiOperation(value = “使用者注冊”,notes = “使用者注冊接口”)

還可以在實體類上進一步設定詳細的資訊,如下

package com.lyl.pojo;

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

import javax.persistence.Column;
import javax.persistence.Id;

@ApiModel(value = "使用者注冊",description = "這是使用者對象")
public class Users {
    @ApiModelProperty(hidden = true)//隐藏參數
    @Id
    private String id;

    /**
     * 使用者名
     *
     * required必填項
     * name字段名字
     */
    @ApiModelProperty(value = "使用者名",name = "username",example = "951922700",required =true )
    private String username;

    /**
     * 密碼
     */
    @ApiModelProperty(value = "密碼",name = "password",example = "943033940",required =true)
    private String password;

    /**
     * 我的頭像,如果沒有預設給一張
     */
    @ApiModelProperty(hidden = true)
    @Column(name = "face_image")
    private String faceImage;

    /**
     * 昵稱
     */
    private String nickname;

    /**
     * 我的粉絲數量
     */
    @ApiModelProperty(hidden = true)
    @Column(name = "fans_counts")
    private Integer fansCounts;

    /**
     * 我關注的人總數
     */
    @ApiModelProperty(hidden = true)
    @Column(name = "follow_counts")
    private Integer followCounts;

    /**
     * 我接受到的贊美/收藏 的數量
     */
    @ApiModelProperty(hidden = true)
    @Column(name = "receive_like_counts")
    private Integer receiveLikeCounts;

    /**
     * @return id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * 擷取使用者名
     *
     * @return username - 使用者名
     */
    public String getUsername() {
        return username;
    }

    /**
     * 設定使用者名
     *
     * @param username 使用者名
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * 擷取密碼
     *
     * @return password - 密碼
     */
    public String getPassword() {
        return password;
    }

    /**
     * 設定密碼
     *
     * @param password 密碼
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * 擷取我的頭像,如果沒有預設給一張
     *
     * @return face_image - 我的頭像,如果沒有預設給一張
     */
    public String getFaceImage() {
        return faceImage;
    }

    /**
     * 設定我的頭像,如果沒有預設給一張
     *
     * @param faceImage 我的頭像,如果沒有預設給一張
     */
    public void setFaceImage(String faceImage) {
        this.faceImage = faceImage;
    }

    /**
     * 擷取昵稱
     *
     * @return nickname - 昵稱
     */
    public String getNickname() {
        return nickname;
    }

    /**
     * 設定昵稱
     *
     * @param nickname 昵稱
     */
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    /**
     * 擷取我的粉絲數量
     *
     * @return fans_counts - 我的粉絲數量
     */
    public Integer getFansCounts() {
        return fansCounts;
    }

    /**
     * 設定我的粉絲數量
     *
     * @param fansCounts 我的粉絲數量
     */
    public void setFansCounts(Integer fansCounts) {
        this.fansCounts = fansCounts;
    }

    /**
     * 擷取我關注的人總數
     *
     * @return follow_counts - 我關注的人總數
     */
    public Integer getFollowCounts() {
        return followCounts;
    }

    /**
     * 設定我關注的人總數
     *
     * @param followCounts 我關注的人總數
     */
    public void setFollowCounts(Integer followCounts) {
        this.followCounts = followCounts;
    }

    /**
     * 擷取我接受到的贊美/收藏 的數量
     *
     * @return receive_like_counts - 我接受到的贊美/收藏 的數量
     */
    public Integer getReceiveLikeCounts() {
        return receiveLikeCounts;
    }

    /**
     * 設定我接受到的贊美/收藏 的數量
     *
     * @param receiveLikeCounts 我接受到的贊美/收藏 的數量
     */
    public void setReceiveLikeCounts(Integer receiveLikeCounts) {
        this.receiveLikeCounts = receiveLikeCounts;
    }

    @Override
    public String toString() {
        return "Users{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", faceImage='" + faceImage + '\'' +
                ", nickname='" + nickname + '\'' +
                ", fansCounts=" + fansCounts +
                ", followCounts=" + followCounts +
                ", receiveLikeCounts=" + receiveLikeCounts +
                '}';
    }
}
           
  1. 運作項目,通路http://localhost/swagger-ui.html

    可以自行對比剛剛設定的參數對應文檔的什麼資訊

    springboot中使用Swagger2生成接口文檔
    springboot中使用Swagger2生成接口文檔
  2. 最後還可以在這裡進行接口測試
    springboot中使用Swagger2生成接口文檔
    設定好參數後點選try it out
    springboot中使用Swagger2生成接口文檔

繼續閱讀