Spring Boot集成Swagger API在線文檔

關於Swagger
Swagger API在線文檔是連接前後臺開發的一座橋樑,也是後臺開發工程師測試接口的強大工具之一,在Restful軟件架構風格中,幾乎每個項目都集成了Swagger,還記得之前沒用 Swagger的時候,測試接口都要跑PostMan,Get請求還好,參數不算多,遇到表單提交 的POST或者PUT請求的時候,那是一個勁的頭疼,所以今天博主分享一下在Spring Boot項目中集成Swagger。具體介紹就不多說,可到官網查看官網地址

SpringBoot集成Swagger

1. 使用IDEA新建Spring Boot項目
選擇 File->new Project-> Spring Initializr
在這裏插入圖片描述
2.默認選項,如需修改可自行修改
在這裏插入圖片描述3.勾選Web->Spring Web
在這裏插入圖片描述4.在pom.xml文件中添加以下依賴

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

5.添加Swagger配置,新建Swagger配置類文件SwaggerConfig*

package com.example.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
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 api(){
        return  new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //文檔標題
                .title(" Spring Boot RESTful API")
                // 版本號
                .version("1.0")
                // 標題描述
                .description("swagger在線文檔")
                .build();
    }
}

6.到這裏我們的Spring Boot集成Swagger配置就大功告成了,來看一下效果
在這裏插入圖片描述下一篇博客繼續爲小夥伴分享一下如何使用Swagger自動生成接口文檔!

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