SmartSwaggerDynamicGroupConfig.java 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package net.lab1024.smartadmin.config;
  2. import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
  3. import net.lab1024.smartadmin.constant.SwaggerTagConst;
  4. import com.google.common.base.Optional;
  5. import com.google.common.base.Predicate;
  6. import com.google.common.base.Predicates;
  7. import com.google.common.collect.Lists;
  8. import com.google.common.collect.Maps;
  9. import io.swagger.annotations.Api;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.beans.BeansException;
  12. import org.springframework.beans.factory.config.BeanDefinition;
  13. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
  14. import org.springframework.beans.factory.support.BeanDefinitionBuilder;
  15. import org.springframework.beans.factory.support.BeanDefinitionRegistry;
  16. import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
  17. import org.springframework.context.EnvironmentAware;
  18. import org.springframework.context.annotation.Configuration;
  19. import org.springframework.context.annotation.Profile;
  20. import org.springframework.core.env.Environment;
  21. import org.springframework.web.bind.annotation.RestController;
  22. import springfox.documentation.RequestHandler;
  23. import springfox.documentation.builders.ApiInfoBuilder;
  24. import springfox.documentation.builders.PathSelectors;
  25. import springfox.documentation.builders.RequestHandlerSelectors;
  26. import springfox.documentation.service.*;
  27. import springfox.documentation.spi.DocumentationType;
  28. import springfox.documentation.spi.service.contexts.SecurityContext;
  29. import springfox.documentation.spring.web.plugins.Docket;
  30. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  31. import java.lang.reflect.Field;
  32. import java.lang.reflect.Modifier;
  33. import java.util.ArrayList;
  34. import java.util.Arrays;
  35. import java.util.List;
  36. import java.util.Map;
  37. /**
  38. * [ 根据SwaggerTagConst内部类动态生成Swagger group ]
  39. *
  40. * @author yandanyang
  41. * @version 1.0
  42. * @company 1024lab.net
  43. * @copyright (c) 2018 1024lab.netInc. All rights reserved.
  44. * @date 2019/8/7 0007 下午 19:20
  45. * @since JDK1.8
  46. */
  47. @Slf4j
  48. @EnableSwagger2
  49. @EnableKnife4j
  50. @Configuration
  51. @Profile({"dev", "sit", "pre", "prod"})
  52. public class SmartSwaggerDynamicGroupConfig implements EnvironmentAware, BeanDefinitionRegistryPostProcessor {
  53. /**
  54. * 分组名称
  55. */
  56. private String apiGroupName;
  57. /**
  58. * 文档标题
  59. */
  60. private String title;
  61. /**
  62. * 文档描述
  63. */
  64. private String description;
  65. /**
  66. * api版本
  67. */
  68. private String version;
  69. /**
  70. * service url
  71. */
  72. private String serviceUrl;
  73. /**
  74. * controller 包路径
  75. */
  76. private String packAge;
  77. private int groupIndex = 0;
  78. private String groupName = "default";
  79. private List<String> groupList = Lists.newArrayList();
  80. private Map<String, List<String>> groupMap = Maps.newHashMap();
  81. @Override
  82. public void setEnvironment(Environment environment) {
  83. this.apiGroupName = environment.getProperty("swagger.apiGroupName");
  84. this.title = environment.getProperty("swagger.title");
  85. this.description = environment.getProperty("swagger.description");
  86. this.version = environment.getProperty("swagger.version");
  87. this.serviceUrl = environment.getProperty("swagger.serviceUrl");
  88. this.packAge = environment.getProperty("swagger.packAge");
  89. }
  90. @Override
  91. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  92. this.groupBuild();
  93. for (Map.Entry<String, List<String>> entry : groupMap.entrySet()) {
  94. String group = entry.getKey();
  95. BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(Docket.class, this :: baseDocket);
  96. BeanDefinition beanDefinition = builder.getRawBeanDefinition();
  97. registry.registerBeanDefinition(group + "Api", beanDefinition);
  98. }
  99. }
  100. private void groupBuild() {
  101. Class clazz = SwaggerTagConst.class;
  102. Class[] innerClazz = clazz.getDeclaredClasses();
  103. for (Class cls : innerClazz) {
  104. String group = cls.getSimpleName();
  105. List<String> apiTags = Lists.newArrayList();
  106. Field[] fields = cls.getDeclaredFields();
  107. for (Field field : fields) {
  108. boolean isFinal = Modifier.isFinal(field.getModifiers());
  109. if (isFinal) {
  110. try {
  111. apiTags.add(field.get(null).toString());
  112. } catch (Exception e) {
  113. log.error("", e);
  114. }
  115. }
  116. }
  117. groupList.add(group);
  118. groupMap.put(group, apiTags);
  119. }
  120. }
  121. private Docket baseDocket() {
  122. // 请求类型过滤规则
  123. Predicate<RequestHandler> controllerPredicate = getControllerPredicate();
  124. // controller 包路径
  125. Predicate<RequestHandler> controllerPackage = RequestHandlerSelectors.basePackage(packAge);
  126. return new Docket(DocumentationType.SWAGGER_2)
  127. .groupName(groupName)
  128. .forCodeGeneration(true)
  129. .select()
  130. .apis(controllerPackage)
  131. .apis(controllerPredicate)
  132. .paths(PathSelectors.any())
  133. .build()
  134. .apiInfo(this.serviceApiInfo())
  135. .securitySchemes(securitySchemes())
  136. .securityContexts(securityContexts());
  137. }
  138. private List<ApiKey> securitySchemes() {
  139. List<ApiKey> apiKeyList= new ArrayList<>();
  140. apiKeyList.add(new ApiKey("x-access-token", "x-access-token", "header"));
  141. return apiKeyList;
  142. }
  143. private List<SecurityContext> securityContexts() {
  144. List<SecurityContext> securityContexts=new ArrayList<>();
  145. securityContexts.add(
  146. SecurityContext.builder()
  147. .securityReferences(defaultAuth())
  148. .forPaths(PathSelectors.any())
  149. .build());
  150. return securityContexts;
  151. }
  152. List<SecurityReference> defaultAuth() {
  153. AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
  154. AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
  155. authorizationScopes[0] = authorizationScope;
  156. List<SecurityReference> securityReferences=new ArrayList<>();
  157. securityReferences.add(new SecurityReference("x-access-token", authorizationScopes));
  158. return securityReferences;
  159. }
  160. private Predicate<RequestHandler> getControllerPredicate() {
  161. groupName = groupList.get(groupIndex);
  162. List<String> apiTags = groupMap.get(groupName);
  163. Predicate<RequestHandler> methodPredicate = (input) -> {
  164. Api api = null;
  165. Optional<Api> apiOptional = input.findControllerAnnotation(Api.class);
  166. if (apiOptional.isPresent()) {
  167. api = apiOptional.get();
  168. }
  169. if(api != null){
  170. List<String> tags = Arrays.asList(api.tags());
  171. if (api != null && apiTags.containsAll(tags)) {
  172. return true;
  173. }
  174. }
  175. return false;
  176. };
  177. groupIndex++;
  178. return Predicates.and(RequestHandlerSelectors.withClassAnnotation(RestController.class), methodPredicate);
  179. }
  180. private ApiInfo serviceApiInfo() {
  181. return new ApiInfoBuilder()
  182. .title(title)
  183. .description(description)
  184. .version(version)
  185. .license("Apache License Version 2.0")
  186. .contact(new Contact("1024创新实验室", "http://www.1024lab.net", ""))
  187. .termsOfServiceUrl(serviceUrl)
  188. .build();
  189. }
  190. @Override
  191. public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
  192. }
  193. }