Swagger筆記之Swagger2配置


@

相關內容 地址
Swagger官方文檔 https://swagger.io/docs/specification/2-0/basic-structure/
Swagger常用注解 https://blog.csdn.net/weixin_42526326/article/details/119824857
Swagger2常用注解 https://blog.csdn.net/weixin_42526326/article/details/119963866
Swagger3常用注解 https://blog.csdn.net/weixin_42526326/article/details/119965092

什么是 Swagger?

Swagger是一組圍繞 OpenAPI 規范構建的開源工具,可幫助您設計、構建、記錄和使用 REST API。主要的 Swagger 工具包括:

Swagger Editor – 基於瀏覽器的編輯器,您可以在其中編寫 OpenAPI 規范。
Swagger UI – 將 OpenAPI 規范呈現為交互式 API 文檔。

swagger2於17年停止維護,現在最新的版本為 Swagger3(Open Api3)。

依賴引入

我們可以去 mvnrepository(maven中央倉庫) 搜索版本,但是建議不要用最新版

        <!-- swagger2  -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!-- 引入swagger-bootstrap-ui包 -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.8.5</version>
        </dependency>

自定義屬性配置 SwaggerProperties.class

根據自己的需求配置屬性

package com.xxx.common.swagger.config;

import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
//application 配置文件路徑
@ConfigurationProperties("swagger")
public class SwaggerProperties
{
    /**
     * 是否開啟swagger
     */
    private Boolean enabled;

    /**
     * swagger會解析的包路徑
     **/
    private String basePackage = "";

    /**
     * swagger會解析的url規則
     **/
    private List<String> basePath = new ArrayList<>();

    /**
     * 在basePath基礎上需要排除的url規則
     **/
    private List<String> excludePath = new ArrayList<>();

    /**
     * 標題
     **/
    private String title = "";

    /**
     * 描述
     **/
    private String description = "";

    /**
     * 版本
     **/
    private String version = "";

    /**
     * 許可證
     **/
    private String license = "";

    /**
     * 許可證URL
     **/
    private String licenseUrl = "";

    /**
     * 服務條款URL
     **/
    private String termsOfServiceUrl = "";

    /**
     * host信息
     **/
    private String host = "";

    /**
     * 聯系人信息
     */
    private Contact contact = new Contact();

    /**
     * 全局統一鑒權配置
     **/
    private Authorization authorization = new Authorization();

    public Boolean getEnabled()
    {
        return enabled;
    }

    public void setEnabled(Boolean enabled)
    {
        this.enabled = enabled;
    }

    public String getBasePackage()
    {
        return basePackage;
    }

    public void setBasePackage(String basePackage)
    {
        this.basePackage = basePackage;
    }

    public List<String> getBasePath()
    {
        return basePath;
    }

    public void setBasePath(List<String> basePath)
    {
        this.basePath = basePath;
    }

    public List<String> getExcludePath()
    {
        return excludePath;
    }

    public void setExcludePath(List<String> excludePath)
    {
        this.excludePath = excludePath;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public String getDescription()
    {
        return description;
    }

    public void setDescription(String description)
    {
        this.description = description;
    }

    public String getVersion()
    {
        return version;
    }

    public void setVersion(String version)
    {
        this.version = version;
    }

    public String getLicense()
    {
        return license;
    }

    public void setLicense(String license)
    {
        this.license = license;
    }

    public String getLicenseUrl()
    {
        return licenseUrl;
    }

    public void setLicenseUrl(String licenseUrl)
    {
        this.licenseUrl = licenseUrl;
    }

    public String getTermsOfServiceUrl()
    {
        return termsOfServiceUrl;
    }

    public void setTermsOfServiceUrl(String termsOfServiceUrl)
    {
        this.termsOfServiceUrl = termsOfServiceUrl;
    }

    public String getHost()
    {
        return host;
    }

    public void setHost(String host)
    {
        this.host = host;
    }

    public Contact getContact()
    {
        return contact;
    }

    public void setContact(Contact contact)
    {
        this.contact = contact;
    }

    public Authorization getAuthorization()
    {
        return authorization;
    }

    public void setAuthorization(Authorization authorization)
    {
        this.authorization = authorization;
    }

    public static class Contact
    {
        /**
         * 聯系人
         **/
        private String name = "";
        /**
         * 聯系人url
         **/
        private String url = "";
        /**
         * 聯系人email
         **/
        private String email = "";

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        public String getUrl()
        {
            return url;
        }

        public void setUrl(String url)
        {
            this.url = url;
        }

        public String getEmail()
        {
            return email;
        }

        public void setEmail(String email)
        {
            this.email = email;
        }
    }

    public static class Authorization
    {
        /**
         * 鑒權策略ID,需要和SecurityReferences ID保持一致
         */
        private String name = "";

        /**
         * 需要開啟鑒權URL的正則
         */
        private String authRegex = "^.*$";

        /**
         * 鑒權作用域列表
         */
        private List<AuthorizationScope> authorizationScopeList = new ArrayList<>();

        private List<String> tokenUrlList = new ArrayList<>();

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        public String getAuthRegex()
        {
            return authRegex;
        }

        public void setAuthRegex(String authRegex)
        {
            this.authRegex = authRegex;
        }

        public List<AuthorizationScope> getAuthorizationScopeList()
        {
            return authorizationScopeList;
        }

        public void setAuthorizationScopeList(List<AuthorizationScope> authorizationScopeList)
        {
            this.authorizationScopeList = authorizationScopeList;
        }

        public List<String> getTokenUrlList()
        {
            return tokenUrlList;
        }

        public void setTokenUrlList(List<String> tokenUrlList)
        {
            this.tokenUrlList = tokenUrlList;
        }
    }

    public static class AuthorizationScope
    {
        /**
         * 作用域名稱
         */
        private String scope = "";

        /**
         * 作用域描述
         */
        private String description = "";

        public String getScope()
        {
            return scope;
        }

        public void setScope(String scope)
        {
            this.scope = scope;
        }

        public String getDescription()
        {
            return description;
        }

        public void setDescription(String description)
        {
            this.description = description;
        }
    }
}

詳細配置

配置文件加上@EnableSwagger2、@Configuration 會自動開啟配置,啟動類不需要加任何注解

package com.xxx.interceptor.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 * @author yaokun.zhang
 */
@Configuration
//是否開啟swagger配置,生產環境需關閉
@Profile({"dev","local"})
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig {

    /**
     * 是否開啟swagger配置,生產環境需關閉
     */
	/*@Value("${swagger.enabled}")
    private boolean enable;*/

    /**
     * 創建API
     * http:IP:端口號/swagger-ui/ 原生地址
     * http:IP:端口號/doc.html bootStrap-UI地址
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).pathMapping("/")
                // 用來創建該API的基本信息,展示在文檔的頁面中(自定義展示的信息)
                /*.enable(enable)*/
                .apiInfo(apiInfo())
                // 設置哪些接口暴露給Swagger展示
                .select()
                // 掃描所有有注解的api,用這種方式更靈活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 掃描指定包中的swagger注解
                // .apis(RequestHandlerSelectors.basePackage("com.doctorcloud.product.web.controller"))
                // 掃描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("(?!/ApiError.*).*"))
                .paths(PathSelectors.any())
                .build()
                // 支持的通訊協議集合
                .protocols(newHashSet("https", "http"))
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());

    }

    /**
     * 支持的通訊協議集合
     * @param type1
     * @param type2
     * @return
     */
    private Set<String> newHashSet(String type1, String type2){
        Set<String> set = new HashSet<>();
        set.add(type1);
        set.add(type2);
        return set;
    }

    /**
     * 認證的安全上下文
     */
    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> securitySchemes = new ArrayList<>();
        securitySchemes.add(new ApiKey("token", "token", "header"));
        return securitySchemes;
    }

    /**
     * 授權信息全局應用
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any()).build());
        return securityContexts;
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder進行定制
        return new ApiInfoBuilder()
                // 設置標題
                .title("接口文檔")
                // 描述
                .description("描述")
                // 作者信息
                .contact(new Contact("doctorCloud", null, null))
                // 版本
                .version("版本號:V.1")
                //協議
                .license("The Apache License")
                //協議url
                .licenseUrl("")
                .build();
    }
}

swagger資源訪問路徑加入白名單

- /swagger-ui.html
- /doc.html
- /swagger-resources/**
- /v2/api-docs

訪問路徑:

http:IP:端口號/swagger-ui.html 原生地址
http:IP:端口號/doc.html bootStrap-UI地址

小技巧:

不建議使用swagger原生頁面設置權限,建議使用doc頁面設置token,搜索接口更方便
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM