Merge pull request #8116 from EightMonth/springboot3

优化swagger文档改造
pull/8256/head
JEECG 2025-04-15 11:41:44 +08:00 committed by GitHub
commit 2ba17648c4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 209 additions and 220 deletions

View File

@ -3,7 +3,6 @@ package org.jeecg.config;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
@ -12,9 +11,10 @@ import io.swagger.v3.oas.models.security.SecurityScheme;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springdoc.core.models.GroupedOpenApi;
import org.springdoc.core.filters.GlobalOpenApiMethodFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ -27,6 +27,7 @@ import java.util.Set;
*/
@Slf4j
@Configuration
@PropertySource("classpath:config/default-spring-doc.properties")
public class Swagger3Config implements WebMvcConfigurer {
// 定义不需要注入安全要求的路径集合
Set<String> excludedPaths = new HashSet<>(Arrays.asList(
@ -55,16 +56,8 @@ public class Swagger3Config implements WebMvcConfigurer {
}
@Bean
public GroupedOpenApi swaggerOpenApi() {
return GroupedOpenApi.builder()
.group("default")
.packagesToScan("org.jeecg")
// 剔除以下几个包路径的接口生成文档
.packagesToExclude("org.jeecg.modules.drag", "org.jeecg.modules.online", "org.jeecg.modules.jmreport")
// 加了Operation注解的方法才生成接口文档
.addOpenApiMethodFilter(method -> method.isAnnotationPresent(Operation.class))
.addOpenApiCustomizer(globalOpenApiCustomizer())
.build();
public GlobalOpenApiMethodFilter globalOpenApiMethodFilter() {
return method -> method.isAnnotationPresent(Operation.class);
}
@Bean

View File

@ -0,0 +1,2 @@
springdoc.auto-tag-classes: false
springdoc.packages-to-scan: org.jeecg

View File

@ -306,7 +306,6 @@ logging:
level:
org.flywaydb: debug
org.jeecg.modules.system.mapper: info
#swagger
knife4j:
#开启增强配置
enable: true

View File

@ -73,7 +73,7 @@
<!-- Swagger API文档 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-gateway-spring-boot-starter</artifactId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>${knife4j-spring-boot-starter.version}</version>
</dependency>
<dependency>

View File

@ -1,160 +1,160 @@
//package org.jeecg.handler.swagger;
//
//import cn.hutool.core.util.ArrayUtil;
//import cn.hutool.core.util.ObjectUtil;
//import com.alibaba.nacos.api.naming.NamingFactory;
//import com.alibaba.nacos.api.naming.NamingService;
//import com.alibaba.nacos.api.naming.pojo.Instance;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cloud.gateway.route.RouteLocator;
//import org.springframework.context.annotation.Primary;
//import org.springframework.stereotype.Component;
//
//import springfox.documentation.swagger.web.SwaggerResource;
//import springfox.documentation.swagger.web.SwaggerResourcesProvider;
//
//import java.util.*;
//
///** 已使用knife4j-gateway支持该功能
// * 聚合各个服务的swagger接口
// * @author zyf
// * @date: 2022/4/21 10:55
// */
//@Component
//@Slf4j
//@Primary
//public class MySwaggerResourceProvider implements SwaggerResourcesProvider {
// /**
// * swagger2默认的url后缀
// */
// private static final String SWAGGER2URL = "/v2/api-docs";
//
// /**
// * 网关路由
// */
// private final RouteLocator routeLocator;
// /**
// * Nacos名字服务
// */
// private NamingService naming;
//
// /**
// * nacos服务地址
// */
// @Value("${spring.cloud.nacos.discovery.server-addr}")
// private String serverAddr;
// /**
// * nacos namespace
// */
// @Value("${spring.cloud.nacos.discovery.namespace:#{null}}")
// private String namespace;
//
// /**
// * nacos groupName
// */
// @Value("${spring.cloud.nacos.config.group:DEFAULT_GROUP:#{null}}")
// private String group;
//
// /**
// * nacos username
// */
// @Value("${spring.cloud.nacos.discovery.username:#{null}}")
// private String username;
// /**
// * nacos password
// */
// @Value("${spring.cloud.nacos.discovery.password:#{null}}")
// private String password;
//
// /**
// * Swagger中需要排除的服务
// */
// private String[] excludeServiceIds=new String[]{"jeecg-cloud-monitor"};
//
//
// /**
// * 网关应用名称
// */
// @Value("${spring.application.name}")
// private String self;
//
// @Autowired
// public MySwaggerResourceProvider(RouteLocator routeLocator) {
// this.routeLocator = routeLocator;
// }
//
// @Override
// public List<SwaggerResource> get() {
// List<SwaggerResource> resources = new ArrayList<>();
// List<String> routeHosts = new ArrayList<>();
// // 获取所有可用的hostserviceId
// routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
// .filter(route -> !self.equals(route.getUri().getHost()))
// .subscribe(route ->{
// //update-begin---author:zyf ---date:20220413 for过滤掉无效路由,避免接口文档报错无法打开
// boolean hasRoute=checkRoute(route.getId());
// if(hasRoute){
// routeHosts.add(route.getUri().getHost());
// }
// //update-end---author:zyf ---date:20220413 for过滤掉无效路由,避免接口文档报错无法打开
// });
//
// // 记录已经添加过的server存在同一个应用注册了多个服务在nacos上
// Set<String> dealed = new HashSet<>();
// routeHosts.forEach(instance -> {
// // 拼接url
// String url = "/" + instance.toLowerCase() + SWAGGER2URL;
// if (!dealed.contains(url)) {
// dealed.add(url);
// log.info(" Gateway add SwaggerResource: {}",url);
// SwaggerResource swaggerResource = new SwaggerResource();
// swaggerResource.setUrl(url);
// swaggerResource.setSwaggerVersion("2.0");
// swaggerResource.setName(instance);
// //Swagger排除不展示的服务
// if(!ArrayUtil.contains(excludeServiceIds,instance)){
// resources.add(swaggerResource);
// }
// }
// });
// return resources;
// }
//
// /**
// * 检测nacos中是否有健康实例
// * @param routeId
// * @return
// */
// private Boolean checkRoute(String routeId) {
// Boolean hasRoute = false;
// try {
// //修复使用带命名空间启动网关swagger看不到接口文档的问题
// Properties properties=new Properties();
// properties.setProperty("serverAddr",serverAddr);
// if(namespace!=null && !"".equals(namespace)){
// log.info("nacos.discovery.namespace = {}", namespace);
// properties.setProperty("namespace",namespace);
// }
// if(username!=null && !"".equals(username)){
// properties.setProperty("username",username);
// }
// if(password!=null && !"".equals(password)){
// properties.setProperty("password",password);
// }
// //【issues/5115】因swagger文档导致gateway内存溢出
// if (this.naming == null) {
// this.naming = NamingFactory.createNamingService(properties);
// }
// log.info(" config.group : {}", group);
// List<Instance> list = this.naming.selectInstances(routeId, group , true);
// if (ObjectUtil.isNotEmpty(list)) {
// hasRoute = true;
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return hasRoute;
// }
//}
package org.jeecg.handler.swagger;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.*;
/** 使knife4j-gateway
* swagger
* @author zyf
* @date: 2022/4/21 10:55
*/
@Component
@Slf4j
@Primary
public class MySwaggerResourceProvider implements SwaggerResourcesProvider {
/**
* swagger2url
*/
private static final String SWAGGER2URL = "/v3/api-docs";
/**
*
*/
private final RouteLocator routeLocator;
/**
* Nacos
*/
private NamingService naming;
/**
* nacos
*/
@Value("${spring.cloud.nacos.discovery.server-addr}")
private String serverAddr;
/**
* nacos namespace
*/
@Value("${spring.cloud.nacos.discovery.namespace:#{null}}")
private String namespace;
/**
* nacos groupName
*/
@Value("${spring.cloud.nacos.config.group:DEFAULT_GROUP:#{null}}")
private String group;
/**
* nacos username
*/
@Value("${spring.cloud.nacos.discovery.username:#{null}}")
private String username;
/**
* nacos password
*/
@Value("${spring.cloud.nacos.discovery.password:#{null}}")
private String password;
/**
* Swagger
*/
private String[] excludeServiceIds=new String[]{"jeecg-cloud-monitor"};
/**
*
*/
@Value("${spring.application.name}")
private String self;
@Autowired
public MySwaggerResourceProvider(RouteLocator routeLocator) {
this.routeLocator = routeLocator;
}
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routeHosts = new ArrayList<>();
// 获取所有可用的hostserviceId
routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
.filter(route -> !self.equals(route.getUri().getHost()))
.subscribe(route ->{
//update-begin---author:zyf ---date:20220413 for过滤掉无效路由,避免接口文档报错无法打开
boolean hasRoute=checkRoute(route.getId());
if(hasRoute){
routeHosts.add(route.getUri().getHost());
}
//update-end---author:zyf ---date:20220413 for过滤掉无效路由,避免接口文档报错无法打开
});
// 记录已经添加过的server存在同一个应用注册了多个服务在nacos上
Set<String> dealed = new HashSet<>();
routeHosts.forEach(instance -> {
// 拼接url
String url = "/" + instance.toLowerCase() + SWAGGER2URL;
if (!dealed.contains(url)) {
dealed.add(url);
log.info(" Gateway add SwaggerResource: {}",url);
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setUrl(url);
swaggerResource.setSwaggerVersion("2.0");
swaggerResource.setName(instance);
//Swagger排除不展示的服务
if(!ArrayUtil.contains(excludeServiceIds,instance)){
resources.add(swaggerResource);
}
}
});
return resources;
}
/**
* nacos
* @param routeId
* @return
*/
private Boolean checkRoute(String routeId) {
Boolean hasRoute = false;
try {
//修复使用带命名空间启动网关swagger看不到接口文档的问题
Properties properties=new Properties();
properties.setProperty("serverAddr",serverAddr);
if(namespace!=null && !"".equals(namespace)){
log.info("nacos.discovery.namespace = {}", namespace);
properties.setProperty("namespace",namespace);
}
if(username!=null && !"".equals(username)){
properties.setProperty("username",username);
}
if(password!=null && !"".equals(password)){
properties.setProperty("password",password);
}
//【issues/5115】因swagger文档导致gateway内存溢出
if (this.naming == null) {
this.naming = NamingFactory.createNamingService(properties);
}
log.info(" config.group : {}", group);
List<Instance> list = this.naming.selectInstances(routeId, group , true);
if (ObjectUtil.isNotEmpty(list)) {
hasRoute = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return hasRoute;
}
}

View File

@ -1,41 +1,41 @@
//package org.jeecg.handler.swagger;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//import springfox.documentation.swagger.web.*;
//
//import java.util.List;
//
///** 已使用knife4j-gateway支持该功能
// * swagger聚合接口三个接口都是 doc.html需要访问的接口
// * @author zyf
// * @date: 2022/4/21 10:55
// */
//@RestController
//@RequestMapping("/swagger-resources")
//public class SwaggerResourceController {
// private MySwaggerResourceProvider swaggerResourceProvider;
//
// @Autowired
// public SwaggerResourceController(MySwaggerResourceProvider swaggerResourceProvider) {
// this.swaggerResourceProvider = swaggerResourceProvider;
// }
//
// @RequestMapping(value = "/configuration/security")
// public ResponseEntity<SecurityConfiguration> securityConfiguration() {
// return new ResponseEntity<>(SecurityConfigurationBuilder.builder().build(), HttpStatus.OK);
// }
//
// @RequestMapping(value = "/configuration/ui")
// public ResponseEntity<UiConfiguration> uiConfiguration() {
// return new ResponseEntity<>(UiConfigurationBuilder.builder().build(), HttpStatus.OK);
// }
//
// @RequestMapping
// public ResponseEntity<List<SwaggerResource>> swaggerResources() {
// return new ResponseEntity<>(swaggerResourceProvider.get(), HttpStatus.OK);
// }
//}
package org.jeecg.handler.swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger.web.*;
import java.util.List;
/** 使knife4j-gateway
* swagger doc.html访
* @author zyf
* @date: 2022/4/21 10:55
*/
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerResourceController {
private MySwaggerResourceProvider swaggerResourceProvider;
@Autowired
public SwaggerResourceController(MySwaggerResourceProvider swaggerResourceProvider) {
this.swaggerResourceProvider = swaggerResourceProvider;
}
@RequestMapping(value = "/configuration/security")
public ResponseEntity<SecurityConfiguration> securityConfiguration() {
return new ResponseEntity<>(SecurityConfigurationBuilder.builder().build(), HttpStatus.OK);
}
@RequestMapping(value = "/configuration/ui")
public ResponseEntity<UiConfiguration> uiConfiguration() {
return new ResponseEntity<>(UiConfigurationBuilder.builder().build(), HttpStatus.OK);
}
@RequestMapping
public ResponseEntity<List<SwaggerResource>> swaggerResources() {
return new ResponseEntity<>(swaggerResourceProvider.get(), HttpStatus.OK);
}
}

View File

@ -1,11 +1,6 @@
server:
port: 7001
springdoc:
packages-to-exclude:
- org.jeecg.modules.drag
- org.jeecg.modules.online
- org.jeecg.modules.jmreport
spring:
application:
name: jeecg-system