Skip to content

Commit

Permalink
♻️ Refactoring code. 重构 common-swagger 模块
Browse files Browse the repository at this point in the history
  • Loading branch information
lbw committed Aug 29, 2023
1 parent cca691b commit 64903a4
Show file tree
Hide file tree
Showing 5 changed files with 118 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package com.pig4cloud.pig.common.swagger.annotation;

import com.pig4cloud.pig.common.swagger.config.SwaggerAutoConfiguration;
import com.pig4cloud.pig.common.swagger.config.OpenAPIDefinitionImportSelector;
import com.pig4cloud.pig.common.swagger.support.SwaggerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
Expand All @@ -34,7 +34,13 @@
@Documented
@Inherited
@EnableConfigurationProperties(SwaggerProperties.class)
@Import({ SwaggerAutoConfiguration.class })
@Import({ OpenAPIDefinitionImportSelector.class })
public @interface EnablePigDoc {

/**
* 网关路由前缀
* @return String
*/
String value();

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springdoc.core.SpringDocUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.context.annotation.Bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpHeaders;

import java.util.ArrayList;
Expand All @@ -40,40 +42,24 @@
*
* <p>
* 禁用方法1:使用注解@Profile({"dev","test"})
*
* <p>
* 表示在开发或测试环境开启,而在生产关闭。(推荐使用) 禁用方法2:使用注解@ConditionalOnProperty(name = "swagger.enable",
*
* <p>
* havingValue = "true") 然后在测试配置或者开发配置中添加swagger.enable=true即可开启,生产环境不填则默认关闭Swagger.
* </p>
*
* @author lengleng
*/
@RequiredArgsConstructor
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
@ConditionalOnMissingClass("org.springframework.cloud.gateway.config.GatewayAutoConfiguration")
public class SwaggerAutoConfiguration {

private final SwaggerProperties swaggerProperties;
public class OpenAPIDefinition extends OpenAPI implements InitializingBean, ApplicationContextAware {

private final ServiceInstance serviceInstance;
@Setter
private String path;

@Bean
public OpenAPI springOpenAPI() {
OpenAPI openAPI = new OpenAPI().info(new Info().title(swaggerProperties.getTitle()));
// oauth2.0 password
openAPI.schemaRequirement(HttpHeaders.AUTHORIZATION, this.securityScheme());
// servers
List<Server> serverList = new ArrayList<>();
String path = swaggerProperties.getServices().get(serviceInstance.getServiceId());
serverList.add(new Server().url(swaggerProperties.getGateway() + "/" + path));
openAPI.servers(serverList);
private ApplicationContext applicationContext;

// 支持参数平铺
SpringDocUtils.getConfig().addSimpleTypesForParameterObject(Class.class);
return openAPI;
}

private SecurityScheme securityScheme() {
private SecurityScheme securityScheme(SwaggerProperties swaggerProperties) {
OAuthFlow clientCredential = new OAuthFlow();
clientCredential.setTokenUrl(swaggerProperties.getTokenUrl());
clientCredential.setScopes(new Scopes().addString(swaggerProperties.getScope(), swaggerProperties.getScope()));
Expand All @@ -85,4 +71,23 @@ private SecurityScheme securityScheme() {
return securityScheme;
}

@Override
public void afterPropertiesSet() throws Exception {
SwaggerProperties swaggerProperties = applicationContext.getBean(SwaggerProperties.class);
this.info(new Info().title(swaggerProperties.getTitle()));
// oauth2.0 password
this.schemaRequirement(HttpHeaders.AUTHORIZATION, this.securityScheme(swaggerProperties));
// servers
List<Server> serverList = new ArrayList<>();
serverList.add(new Server().url(swaggerProperties.getGateway() + "/" + path));
this.servers(serverList);
// 支持参数平铺
SpringDocUtils.getConfig().addSimpleTypesForParameterObject(Class.class);
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.pig4cloud.pig.common.swagger.config;

import com.pig4cloud.pig.common.swagger.annotation.EnablePigDoc;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;
import java.util.Objects;

/**
* openapi 配置类
*
* @author lengleng
* @date 2023/1/1
*/
public class OpenAPIDefinitionImportSelector implements ImportBeanDefinitionRegistrar {

@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {

Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(EnablePigDoc.class.getName(), true);
Object value = annotationAttributes.get("value");
if (Objects.isNull(value)) {
return;
}

BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(OpenAPIDefinition.class);
definition.addPropertyValue("path", value);

registry.registerBeanDefinition("openAPIDefinition", definition.getBeanDefinition());

// 如果是微服务架构则,引入了服务发现声明相关的元数据配置
Object isMicro = annotationAttributes.getOrDefault("isMicro", true);
if (isMicro.equals(false)) {
return;
}

BeanDefinitionBuilder openAPIMetadata = BeanDefinitionBuilder
.genericBeanDefinition(OpenAPIMetadataConfiguration.class);
openAPIMetadata.addPropertyValue("path", value);
registry.registerBeanDefinition("openAPIMetadata", openAPIMetadata.getBeanDefinition());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.pig4cloud.pig.common.swagger.config;

import lombok.Setter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
* @author lengleng
* @date 2023/1/4
*/
public class OpenAPIMetadataConfiguration implements InitializingBean, ApplicationContextAware {

private ApplicationContext applicationContext;

@Setter
private String path;

@Override
public void afterPropertiesSet() throws Exception {
ServiceInstance serviceInstance = applicationContext.getBean(ServiceInstance.class);
serviceInstance.getMetadata().put("spring-doc", path);
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
* <p>
* 用户统一管理系统
*/
@EnablePigDoc
@EnablePigDoc("admin")
@EnablePigFeignClients
@EnablePigResourceServer
@EnableDiscoveryClient
Expand Down

0 comments on commit 64903a4

Please sign in to comment.