Browse Source

新增 swagger 3

FanQun 2 years ago
parent
commit
67c05b317e

+ 1 - 1
pom.xml

@@ -28,7 +28,7 @@
         <dependency>
             <groupId>com.github.xiaoymin</groupId>
             <artifactId>knife4j-spring-boot-starter</artifactId>
-            <version>2.0.7</version>
+            <version>3.0.3</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>

+ 123 - 0
src/main/java/com/rshy/project/hy/config/SwaggerConfig.java

@@ -0,0 +1,123 @@
+package com.rshy.project.hy.config;
+
+import io.swagger.models.auth.In;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.springframework.boot.SpringBootVersion;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.util.ReflectionUtils;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+import springfox.documentation.builders.ApiInfoBuilder;
+import springfox.documentation.builders.PathSelectors;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.oas.annotations.EnableOpenApi;
+import springfox.documentation.service.*;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spi.service.contexts.SecurityContext;
+import springfox.documentation.spring.web.plugins.Docket;
+
+import java.lang.reflect.Field;
+import java.util.*;
+
+/**
+ * @author Simon.z
+ * @since 2020/12/30
+ */
+@Configuration
+@EnableOpenApi
+public class SwaggerConfig implements WebMvcConfigurer {
+    private final SwaggerProperties swaggerProperties;
+
+    public SwaggerConfig(SwaggerProperties swaggerProperties) {
+        this.swaggerProperties = swaggerProperties;
+    }
+
+    @Bean
+    public Docket createRestApi() {
+        return new Docket(DocumentationType.OAS_30).pathMapping("/")
+                // 定义是否开启swagger,false为关闭,可以通过变量控制
+                .enable(swaggerProperties.getEnable())
+                // 将api的元信息设置为包含在json ResourceListing响应中。
+                .apiInfo(apiInfo())
+                // 接口调试地址
+                .host(swaggerProperties.getTryHost())
+                // 选择哪些接口作为swagger的doc发布
+                .select()
+                .apis(RequestHandlerSelectors.any())
+                .paths(PathSelectors.any())
+                .build()
+                // 支持的通讯协议集合
+                .protocols(newHashSet("https", "http"))
+                // 授权信息设置,必要的header token等认证信息
+                .securitySchemes(securitySchemes())
+                // 授权信息全局应用
+                .securityContexts(securityContexts());
+    }
+
+    /**
+     * API 页面上半部分展示信息
+     *
+     * @return
+     */
+    private ApiInfo apiInfo() {
+        return new ApiInfoBuilder().title(swaggerProperties.getApplicationName() + " Api Doc")
+                .description(swaggerProperties.getApplicationDescription())
+                .contact(new Contact("simple_box", null, "fq@heishitech.com"))
+                .version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion())
+                .build();
+    }
+
+    /**
+     * 设置授权信息
+     */
+    private List<SecurityScheme> securitySchemes() {
+        ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
+        return Collections.singletonList(apiKey);
+    }
+
+    /**
+     * 授权信息全局应用
+     */
+    private List<SecurityContext> securityContexts() {
+        return Collections.singletonList(
+                SecurityContext.builder()
+                        .securityReferences(Collections.singletonList(
+                                new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{
+                                        new AuthorizationScope("global", "")})))
+                        .build()
+        );
+    }
+
+    @SafeVarargs
+    private final <T> Set<T> newHashSet(T... ts) {
+        if (ts.length > 0) {
+            return new LinkedHashSet<>(Arrays.asList(ts));
+        }
+        return null;
+    }
+
+    /**
+     * 通用拦截器排除swagger设置,所有拦截器都会自动加swagger相关的资源排除信息
+     */
+    @SuppressWarnings("unchecked")
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        try {
+            Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
+            List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
+            if (registrations != null) {
+                for (InterceptorRegistration interceptorRegistration : registrations) {
+                    interceptorRegistration
+                            .excludePathPatterns("/swagger**/**")
+                            .excludePathPatterns("/webjars/**")
+                            .excludePathPatterns("/v3/**")
+                            .excludePathPatterns("/doc.html");
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 2 - 2
src/main/java/com/rshy/project/hy/config/SwaggerConfiguration.java

@@ -9,8 +9,8 @@ import springfox.documentation.spi.DocumentationType;
 import springfox.documentation.spring.web.plugins.Docket;
 import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
 
-@Configuration
-@EnableSwagger2WebMvc
+//@Configuration
+//@EnableSwagger2WebMvc
 //@Configuration
 //@EnableSwagger2
 public class SwaggerConfiguration {

+ 82 - 0
src/main/java/com/rshy/project/hy/config/SwaggerProperties.java

@@ -0,0 +1,82 @@
+package com.rshy.project.hy.config;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+/**
+ * @author Simon.z
+ * @since 2020/12/30
+ */
+@Component
+public class SwaggerProperties {
+
+    /**
+     * 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
+     */
+    @Value("${swagger.enable}")
+    private Boolean enable;
+
+    /**
+     * 项目应用名
+     */
+    @Value("${swagger.application-name}")
+    private String applicationName;
+
+    /**
+     * 项目版本信息
+     */
+    @Value("${swagger.application-version}")
+    private String applicationVersion;
+
+    /**
+     * 项目描述信息
+     */
+    @Value("${swagger.application-description}")
+    private String applicationDescription;
+
+    /**
+     * 接口调试地址
+     */
+    @Value("${swagger.try-host}")
+    private String tryHost;
+
+    public Boolean getEnable() {
+        return enable;
+    }
+
+    public void setEnable(Boolean enable) {
+        this.enable = enable;
+    }
+
+    public String getApplicationName() {
+        return applicationName;
+    }
+
+    public void setApplicationName(String applicationName) {
+        this.applicationName = applicationName;
+    }
+
+    public String getApplicationVersion() {
+        return applicationVersion;
+    }
+
+    public void setApplicationVersion(String applicationVersion) {
+        this.applicationVersion = applicationVersion;
+    }
+
+    public String getApplicationDescription() {
+        return applicationDescription;
+    }
+
+    public void setApplicationDescription(String applicationDescription) {
+        this.applicationDescription = applicationDescription;
+    }
+
+    public String getTryHost() {
+        return tryHost;
+    }
+
+    public void setTryHost(String tryHost) {
+        this.tryHost = tryHost;
+    }
+}

+ 0 - 2
src/main/resources/application-prod.yml

@@ -22,8 +22,6 @@ spring:
         #最小等待连接中的数量,设0为没有限制
         min-idle: 5
 
-swagger:
-  enabled: true
 
 #公安网代理服务
 itfw:

+ 8 - 5
src/main/resources/application.yml

@@ -24,12 +24,15 @@ mybatis-plus:
     map-underscore-to-camel-case: true
     log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
 
-# Swagger配置
+# ===== 自定义swagger配置 ===== #
 swagger:
-  # 是否开启swagger
-  enabled: true
-  # 请求前缀
-  pathMapping:
+  enable: true
+  application-name: 智能证码通核验接口
+  application-version: 1.2.4
+  application-description: 智能证码通核验接口
+  try-host: http://localhost:${server.port}
+
+
 
 base:
   url: "http://10.118.128.114/agentProxy/agent/agentApi"