SpringBoot整合Swagger2(完整版)

寫在前面: 從2018年底開始學習SpringBoot,也用SpringBoot寫過一些項目。這裏對學習Springboot的一些知識總結記錄一下。如果你也在學習SpringBoot,可以關注我,一起學習,一起進步。

相關文章:

【Springboot系列】Springboot入門到項目實戰



Swagger簡介

1、爲什麼要用Swagger

在平時開發中,一個好的API文檔可以減少大量的溝通成本,還可以幫助新加入項目的同事快速上手業務。大家都知道平時開發時,接口變化總是很多,有了變化就要去維護,也是一件比較頭大的事情。尤其是現在前後端分離情況,更容易造成文檔和代碼不一致。這時,我們可以通過Swagger2來使接口規範,方便維護。

2、Swagger簡介

Swagger是一款Restful接口的文檔在線自動生成和功能測試功能軟件。
Swagger是一個規範和完整的框架,用於生成、描述、調用和可視化Restful風格的Web服務。總體目標是使客戶端和文件系統作爲服務器以同樣的速度來更新文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。

Springboot整合Swagger

1、項目結構

在這裏插入圖片描述

2、Swagger依賴

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

3、Swagger配置文件

import org.springframework.beans.factory.annotation.Value;
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;

/**
 1. swagger配置類
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //是否開啓 (true 開啓  false隱藏。生產環境建議隱藏)
                //.enable(false)
                .select()
                //掃描的路徑包,設置basePackage會將包下的所有被@Api標記類的所有方法作爲api
                .apis(RequestHandlerSelectors.basePackage("com.mcy.springbootswagger.controller"))
                //指定路徑處理PathSelectors.any()代表所有的路徑
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //設置文檔標題(API名稱)
                .title("SpringBoot中使用Swagger2接口規範")
                //文檔描述
                .description("接口說明")
                //服務條款URL
                .termsOfServiceUrl("http://localhost:8080/")
                //版本號
                .version("1.0.0")
                .build();
    }
}

【注】@Configuration註解,配置文件,就不多解釋了。@EnableSwagger2的作用是啓用Swagger2相關功能。
Docket對象包含三個方面信息:
2. 整個API的描述信息,即ApiInfo對象包括的信息,這部分信息會在頁面上展示。
3. 指定生成API文檔的包名。
4. 指定生成API的路徑。

4、測試控制器

import com.mcy.springbootswagger.User.User;
import com.mcy.springbootswagger.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.*;

@RestController
@RequestMapping("/user")
//說明接口文件
@Api(value = "測試接口", tags = "用戶管理相關的接口", description = "用戶測試接口")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 保存數據
     * @param user
     * @return
     */
    @PostMapping(value = "/save")
    //方法參數說明,name參數名;value參數說明,備註;dataType參數類型;required 是否必傳;defaultValue 默認值
    @ApiImplicitParam(name = "user", value = "新增用戶數據")
    //說明是什麼方法(可以理解爲方法註釋)
    @ApiOperation(value = "添加用戶", notes = "添加用戶")
    public String saveUser(User user){
        userService.save(user);
        return "保存成功";
    }

    /**
     * 根據id查詢用戶
     * @param id
     * @return
     */
    @GetMapping(value = "findById")
    @ApiOperation(value = "根據id獲取用戶信息", notes = "根據id查詢用戶信息")
    public User getUser(Integer id){
        return userService.findById(id);
    }

    @DeleteMapping(value = "deleteById")
    @ApiOperation(value = "根據id刪除數據", notes = "刪除用戶")
    public String delete(Integer id){
        userService.deleteById(id);
        return "刪除成功";
    }
}

【注】上述代碼註解的含義註釋已經寫的很清楚了,這裏就不多解釋了。其中Service層中的代碼就是對數據的操作,就不多說了。

5、Swagger頁面訪問

運行項目,輸入http://localhost:8080/swagger-ui.html訪問Swagger頁面,頁面如下:
在這裏插入圖片描述在這裏插入圖片描述
點擊需要測試的接口方法,如圖:
在這裏插入圖片描述
可以看到接口需要的參數,請求地址及接口說明信息。點擊右上角的Try it out即可對接口進行測試。
在這裏插入圖片描述
查詢結果:
在這裏插入圖片描述
這裏這些了部分接口進行測試,可以根據項目需求自行添加其他接口。

6、SpringSecurity中配置

如果Spring Boot項目中集成了Spring Security,接口會被攔截,需要在Spring Security的配置類中重寫configure方法,對接口進行過濾一下。代碼如下:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers("/swagger-ui.html")
            .antMatchers("/v2/**")
            .antMatchers("/swagger-resources/**");
}

最後有什麼不足之處,歡迎大家指出,期待與你的交流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章