溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot整合接口管理工具Swagger怎么使用

發(fā)布時(shí)間:2023-04-15 15:32:29 來源:億速云 閱讀:192 作者:iii 欄目:開發(fā)技術(shù)

這篇“SpringBoot整合接口管理工具Swagger怎么使用”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“SpringBoot整合接口管理工具Swagger怎么使用”文章吧。

一、Swagger簡(jiǎn)介

Swagger 是一系列 RESTful API 的工具,通過 Swagger 可以獲得項(xiàng)目的?種交互式文檔,客戶端 SDK 的自動(dòng)生成等功能。

Swagger 的目標(biāo)是為 REST APIs 定義一個(gè)標(biāo)準(zhǔn)的、與語?言無關(guān)的接口,使人和計(jì)算機(jī)在看不到源碼或者看不到文檔或者不能通過網(wǎng)絡(luò)流量檢測(cè)的情況下,能發(fā)現(xiàn)和理解各種服務(wù)的功能。當(dāng)服務(wù)通過 Swagger 定義,消費(fèi)者就能與遠(yuǎn)程的服務(wù)互動(dòng)通過少量的實(shí)現(xiàn)邏輯。

二、Springboot整合swagger

使用 Spring Boot 集成 Swagger 的理念是,使用用注解來標(biāo)記出需要在 API 文檔中展示的信息,Swagger 會(huì)根據(jù)項(xiàng)目中標(biāo)記的注解來生成對(duì)應(yīng)的 API 文檔。Swagger 被號(hào)稱世界上最流行的 API 工具,它提供了 API 管理的全套解決方案,API 文檔管理需要考慮的因素基本都包含,這里將講解最常用的定制內(nèi)容。

1、添加swagger坐標(biāo)

Spring Boot 集成 Swagger 3 很簡(jiǎn)單,需要引入依賴并做基礎(chǔ)配置即可。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2、Swagger Helloword 實(shí)現(xiàn)

2.1、創(chuàng)建springboot項(xiàng)目

在啟動(dòng)類上加上@EnableOpenApi 注解 啟用swagger api文檔功能

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;

@SpringBootApplication
@EnableOpenApi  //啟動(dòng)swagger api文檔注解
public class SpringBootWithSwaggerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootWithSwaggerApplication.class, args);
    }

}
2.2、寫一個(gè)接口
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 阿水
 * @create 2023-04-11 9:54
 */
@RestController()
public class SwaggerController {
    @GetMapping ("hello")
    public String hello(String params) {
        return "hello swagger"+" param為:"+params;
    }
}

SpringBoot整合接口管理工具Swagger怎么使用

2.3、訪問地址
http://localhost:8080/swagger-ui/index.html

SpringBoot整合接口管理工具Swagger怎么使用

三、常用的配置注解

Swagger 通過注解表明該接口會(huì)生成文檔,包括接口名、請(qǐng)求方法、參數(shù)、返回信息等

1、Api 注解和 ApiOperation 注解

  • @Api

使用在類上,表明是swagger資源,@API擁有兩個(gè)屬性:value、tags。

生成的api文檔會(huì)根據(jù)tags分類,直白的說就是這個(gè)controller中的所有接口生成的接口文檔都會(huì)在tags這個(gè)list下;tags如果有多個(gè)值,會(huì)生成多個(gè)list,每個(gè)list都顯示所有接口

value的作用類似tags,但是不能有多個(gè)值

語法:
  @Api(tags = "用戶操作")
  或
  @Api(tags = {"用戶操作","用戶操作2"})
  • @ApiOperation

使用于在方法上,表示一個(gè)http請(qǐng)求的操作

語法:
    @ApiOperation(value = "", 
                  notes = "", 
                  response = )
屬性說明:
  value:方法說明標(biāo)題
  notes:方法詳細(xì)描述
  response:方法返回值類型

案例:使用@Api和@ApiOperation生成api文檔

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 阿水
 * @create 2023-04-11 9:54
 */
@RestController()
@Api(tags = {"操作用戶"})
public class SwaggerController {
    @GetMapping ("hello")
    @ApiOperation(value = "swagger請(qǐng)求",notes = "阿水的第一個(gè)swagger請(qǐng)求",response = String.class)
    public String hello(String params) {
        return "hello swagger"+" param為:"+params;
    }
}

2、ApiImplicitParams 注解和 ApiImplicitParam

@ApiImplicitParams 注解和 @ApiImplicitParam 用于對(duì)方法中的非對(duì)象參數(shù)(參數(shù)綁定到簡(jiǎn)單類型時(shí)使用。)進(jìn)行說明

語法:
@ApiImplicitParams(value = {
     @ApiImplicitParam(name="", value = "", type = "", required = true, paramType = "", defaultValue  = "")
})

屬性說明:
    name:形參名稱
    value:形參的說明文字
    type:形參類型
    required:該參數(shù)是否必須  true|false
    paramType: 用于描述參數(shù)是以何種方式傳遞到 Controller 的,它的值常見有: path, query, body 和 header 
        path 表示參數(shù)是『嵌在』路徑中的,它和 @PathVariable 參數(shù)注解遙相呼應(yīng);
    	query 表示參數(shù)是以 query string 的形式傳遞到后臺(tái)的(無論是 get 請(qǐng)求攜帶在 url 中,還是 post 請(qǐng)求攜帶在請(qǐng)求體中),它和 @RequestParam 參數(shù)注解遙相呼應(yīng);
    	header 表示參數(shù)是『藏在』請(qǐng)求頭中傳遞到后臺(tái)的,它和 @RequestHeader 參數(shù)注解遙相呼應(yīng)的。
    	form 不常用.
    defaultValue :參數(shù)默認(rèn)值

注意:@ApiImplicitParam 的 name 屬性要和 @RequestParam 或 @PathVariable 的 value 遙相呼應(yīng)。

案例:使用@ApiImplicitParams注解和 @ApiImplicitParam 對(duì)方法參數(shù)進(jìn)行說明

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.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 阿水
 * @create 2023-04-11 9:54
 */
@RestController()
@Api(tags = {"操作用戶"})
public class SwaggerController {
    @GetMapping ("hello")
    @ApiOperation(value = "swagger請(qǐng)求",notes = "阿水的第一個(gè)swagger請(qǐng)求",response = String.class)
    @ApiImplicitParams(value ={
            @ApiImplicitParam(name="param1",
                    value = "參數(shù)名1",
                    type = "String",
                    required = true,
                    paramType = "query",
                    defaultValue  = "阿水所想的默認(rèn)值1" ),
            @ApiImplicitParam(name="param2",
                    value = "參數(shù)名2",
                    type = "String",
                    required = true,
                    paramType = "query",
                    defaultValue  = "阿水所想的默認(rèn)值2" )
    })
    public String hello(String param1,String param2) {
        return "hello swagger"+" param1為:"+param1+"param2為"+param2;
    }
}

SpringBoot整合接口管理工具Swagger怎么使用

3、ApiModel注解和 ApiModelProperty

  • @ApiModel

    用在實(shí)體類上,表示對(duì)類進(jìn)行說明,用于實(shí)體類中的參數(shù)接收說明。

@ApiModel("用戶類")
@Data
public class Users {

    @ApiModelProperty(value = "編碼:主鍵")
    private Integer id;

    @ApiModelProperty(value = "用戶名")
    private String username;

    @ApiModelProperty(value = "密碼")
    private String password;

}

4、ApiResponse 和 ApiResponses

@ApiResponses 注解和 @ApiResponse 標(biāo)注在 Controller 的方法上,用來描述 HTTP 請(qǐng)求的響應(yīng)

/**
     * 添加用戶
     *
     * @param user
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加用戶",notes = "添加用戶信息",response = ResponseResult.class)
    @ApiResponses({ @ApiResponse(code = 200, message = "添加成功", response = ResponseResult.class),
            	    @ApiResponse(code = 500, message = "添加失敗", response = ResponseResult.class) })
    public ResponseResult<Void> addUser(@RequestBody User user) {
        //獲得生成的加密鹽
        user.setSalt(SaltUtils.getSalt());
        int n = userService.addUser(user);
        if (n > 0) {
            return new ResponseResult<Void>(200, "添加成功");
        }
        return new ResponseResult<Void>(500, "添加失敗");
    }

5、創(chuàng)建 SwaggerConfig 配置類

在 SwaggerConfig 中添加兩個(gè)方法:(其中一個(gè)方法是為另一個(gè)方法作輔助的準(zhǔn)備工作)

api()方法使用 @Bean,在啟動(dòng)時(shí)初始化,返回實(shí)例 Docket(Swagger API 摘要對(duì)象),這里需要注意的是 .apis(RequestHandlerSelectors.basePackage("xxx.yyy.zzz")) 指定需要掃描的包路路徑,只有此路徑下的 Controller 類才會(huì)自動(dòng)生成 Swagger API 文檔。

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;

/**
 * Swagger配置類
 */
@Configuration  //項(xiàng)目啟動(dòng)時(shí)加載此類
public class SwaggerConfig {
    @Bean
    public Docket api(){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                // 此處自行修改為自己的 Controller 包路徑。
                .apis(RequestHandlerSelectors.basePackage("com.lps.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    public ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("阿水的項(xiàng)目接口文擋")
                .description("阿水的 Project Swagger2 UserService Interface")  //說明信息
                .termsOfServiceUrl("http://localhost:8080/swagger-ui/index.html") //文檔生成的主頁地址
                .version("1.0")  //文檔版本
                .build();
    }
}

apiInfo()方法配置相對(duì)重要一些,主要配置頁面展示的基本信息包括,標(biāo)題、描述、版本、服務(wù)條款等,查看 ApiInfo 類的源碼還會(huì)發(fā)現(xiàn)支持 license 等更多的配置

四、springsecurity整合swagger

4.1,配置放行的地址

  http.authorizeRequests().antMatchers( "/swagger-ui.html",
                "/swagger-ui/*",
                "/swagger-resources/**",
                "/v2/api-docs",
                "/v3/api-docs",
                "/webjars/**").permitAll()
                .anyRequest().authenticated();

4.2,替換UI

上面的整個(gè)過程已經(jīng)完成了,但是生成的接口文檔的頁面,其實(shí)很多人不太喜歡,覺得不太符合國(guó)人的使用習(xí)慣,所有又有一些大神,提供了其他的UI測(cè)試頁面。這個(gè)頁面的使用還是比較廣泛的。

導(dǎo)入以下依賴、重啟工程后訪問地址:http://localhost:8080/doc.html

	<dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>swagger-bootstrap-ui</artifactId>
        <version>1.9.6</version>
    </dependency>

SpringBoot整合接口管理工具Swagger怎么使用

以上就是關(guān)于“SpringBoot整合接口管理工具Swagger怎么使用”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI