Swagger教程詳解

一、Swagger是什麼?

Swagger是一個面向RESTful API的開源軟件框架。它提供了一組工具,可以幫助您描述、生成、消費API。通過使用Swagger,您可以更好地了解API的工作方式以及如何使用它。

Spring Boot集成Swagger,可以讓我們在開發API文檔時,少寫很多樣板代碼,Swagger生成器會根據註解自動生成API文檔,並且生成的API文檔非常詳細,展示了API的參數、請求方式、響應格式等等。

二、快速上手Swagger

1、首先,在pom.xml中引入Swagger的依賴。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2、創建Swagger2配置類,配置Swagger基本信息

package com.example.swaggerdemo.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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.swaggerdemo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SwaggerDemo API")
                .description("SwaggerDemo後台API接口文檔")
                .termsOfServiceUrl("http://127.0.0.1:8080/")
                .version("1.0")
                .build();
    }
}

3、在Controller層的方法上使用Swagger註解,用於API的說明、請求參數的說明等。

@Api(tags = "用戶管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @ApiOperation(value = "獲取用戶列表")
    @GetMapping("/")
    public List<User> getUserList() {
        return userRepository.findAll();
    }

    @ApiOperation(value = "新增用戶")
    @PostMapping("/")
    public User addUser(@ApiParam(value = "用戶對象", required = true) @RequestBody User user) {
        return userRepository.save(user);
    }

    @ApiOperation(value = "根據ID查詢用戶")
    @GetMapping("/{id}")
    public User getUserById(@ApiParam(value = "用戶ID", required = true) @PathVariable Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @ApiOperation(value = "根據ID更新用戶信息")
    @PutMapping("/{id}")
    public User updateUserById(@ApiParam(value = "用戶ID", required = true) @PathVariable Long id,
                               @ApiParam(value = "用戶對象", required = true) @RequestBody User user) {
        user.setId(id);
        return userRepository.save(user);
    }

    @ApiOperation(value = "根據ID刪除用戶")
    @DeleteMapping("/{id}")
    public void deleteUserById(@ApiParam(value = "用戶ID", required = true) @PathVariable Long id) {
        userRepository.deleteById(id);
    }
}

三、Swagger的常用註解

Swagger常用註解有@Api、@ApiOperation、@ApiParam、@ApiModel、@ApiModelProperty這些註解。

1、@Api:標記一個Controller類為Swagger資源。

2、@ApiOperation:標記Controller方法為Swagger操作。

3、@ApiParam:標記方法參數的名稱和描述。

4、@ApiModel和@ApiModelProperty:用於Swagger Model類的Javadoc。其中,@ApiModel描述模型的名稱和說明,@ApiModelProperty描述模型屬性的名稱、描述信息、是否必須等。

四、Swagger的高級用法

1、全局配置

通過SwaggerConfig的apiInfo()方法,可以設置所有Controller的通用信息。

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("SwaggerDemo API")
            .description("SwaggerDemo後台API接口文檔")
            .termsOfServiceUrl("http://127.0.0.1:8080/")
            .version("1.0")
            .contact(new Contact("SwaggerDemo", "", "xxx@qq.com")) //設置API創建人信息
            .license("Apache License 2.0")
            .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
            .build();
}

2、局部配置

可以在方法級別上對Swagger進行局部配置,例如針對某個方法不展示。

@ApiOperation(value = "獲取用戶列表")
@ApiResponses(value = {
    @ApiResponse(code = 401, message = "未授權"),
    @ApiResponse(code = 403, message = "禁止訪問")
})
@GetMapping("/")
public List<User> getUserList() {
    return userRepository.findAll();
}

3、返回新的數據類型

在Swagger中,我們可以在ResponseBoby註解中使用ResponseContainer註解定義響應數據的格式,常見的格式有List、Set、Map、具體類等。

@ApiOperation(value = "獲取用戶列表")
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "獲取成功", response = User.class, responseContainer = "List")
})
@GetMapping("/")
public List<User> getUserList() {
    return userRepository.findAll();
}

五、Swagger-UI的使用

Swagger-UI是Swagger的前端框架,可以通過Swagger生成的json或yaml文件來展示API文檔。

1、引入Swagger-UI的依賴。

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>swagger-ui</artifactId>
    <version>2.1.4</version>
</dependency>

2、在Spring Boot的配置文件中配置Swagger-UI的訪問路徑。

spring.mvc.static-path-pattern=/swagger/**
spring.resources.static-locations=classpath:/META-INF/resources/webjars/

3、啟用Swagger-UI

在SwaggerConfig類中添加以下代碼:

@Bean
public Docket createApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.swaggerdemo.controller"))
            .paths(PathSelectors.any())
            .build();
}

@Bean
public UiConfiguration getUiConfig() {
    return UiConfigurationBuilder.builder()
            .docExpansion(SwaggerUiConfiguration.DocExpansion.LIST)
            .build();
}

4、訪問Swagger-UI

啟動Spring應用,訪問http://localhost:8080/swagger-ui.html,即可看到Swagger-UI的展示界面。

六、總結

本文詳細闡述了Swagger的概念、快速上手、常用註解、高級用法以及Swagger-UI的使用,是學習Swagger的不錯教程。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/309594.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2025-01-04 19:31
下一篇 2025-01-04 19:31

相關推薦

  • MQTT使用教程

    MQTT是一種輕量級的消息傳輸協議,適用於物聯網領域中的設備與雲端、設備與設備之間的數據傳輸。本文將介紹使用MQTT實現設備與雲端數據傳輸的方法和注意事項。 一、準備工作 在使用M…

    編程 2025-04-29
  • Python3.6.5下載安裝教程

    Python是一種面向對象、解釋型計算機程序語言。它是一門動態語言,因為它不會對程序員提前聲明變量類型,而是在變量第一次賦值時自動識別該變量的類型。 Python3.6.5是Pyt…

    編程 2025-04-29
  • Deepin系統分區設置教程

    本教程將會詳細介紹Deepin系統如何進行分區設置,分享多種方式讓您了解如何規劃您的硬盤。 一、分區的基本知識 在進行Deepin系統分區設置之前,我們需要了解一些基本分區概念。 …

    編程 2025-04-29
  • 寫代碼新手教程

    本文將從語言選擇、學習方法、編碼規範以及常見問題解答等多個方面,為編程新手提供實用、簡明的教程。 一、語言選擇 作為編程新手,選擇一門編程語言是很關鍵的一步。以下是幾個有代表性的編…

    編程 2025-04-29
  • Qt雷達探測教程

    本文主要介紹如何使用Qt開發雷達探測程序,並展示一個簡單的雷達探測示例。 一、環境準備 在開始本教程之前,需要確保你的開發環境已經安裝Qt和Qt Creator。如果沒有安裝,可以…

    編程 2025-04-29
  • 猿編程python免費全套教程400集

    想要學習Python編程嗎?猿編程python免費全套教程400集是一個不錯的選擇!下面我們來詳細了解一下這個教程。 一、課程內容 猿編程python免費全套教程400集包含了從P…

    編程 2025-04-29
  • Python煙花教程

    Python煙花代碼在近年來越來越受到人們的歡迎,因為它可以讓我們在終端里玩煙花,不僅具有視覺美感,還可以通過代碼實現動畫和音效。本教程將詳細介紹Python煙花代碼的實現原理和模…

    編程 2025-04-29
  • 使用Snare服務收集日誌:完整教程

    本教程將介紹如何使用Snare服務收集Windows服務器上的日誌,並將其發送到遠程服務器進行集中管理。 一、安裝和配置Snare 1、下載Snare安裝程序並安裝。 https:…

    編程 2025-04-29
  • Python畫K線教程

    本教程將從以下幾個方面詳細介紹Python畫K線的方法及技巧,包括數據處理、圖表繪製、基本設置等等。 一、數據處理 1、獲取數據 在Python中可以使用Pandas庫獲取K線數據…

    編程 2025-04-28
  • Python語言程序設計教程PDF趙璐百度網盤介紹

    Python語言程序設計教程PDF趙璐百度網盤是一本介紹Python語言編程的入門教材,本文將從以下幾個方面對其進行詳細闡述。 一、Python語言的特點 Python語言屬於解釋…

    編程 2025-04-28

發表回復

登錄後才能評論