Spring動態(tài)加載/卸載Controller并更新Swagger/OpenAPI

直接上代碼,說明文檔后續(xù)再補充

import cn.ac.qibebt.eebd.framework.common.exception.BaseException;
import cn.ac.qibebt.eebd.framework.utils.Check;
import cn.ac.qibebt.eebd.framework.utils.GroovyUtils;
import cn.ac.qibebt.eebd.system.entity.SysScript;
import cn.ac.qibebt.eebd.system.service.SysScriptService;
import io.swagger.v3.oas.models.OpenAPI;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
import org.springdoc.api.AbstractOpenApiResource;
import org.springdoc.core.providers.SpringDocProviders;
import org.springdoc.core.providers.SpringWebProvider;
import org.springdoc.core.service.OpenAPIService;
import org.springdoc.webmvc.api.MultipleOpenApiResource;
import org.springdoc.webmvc.api.OpenApiResource;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.core.MethodIntrospector;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author gx
 * @see <a href="http://www.itdecent.cn/u/aba665c4151f">簡書TinyThing</a>
 * @since 2024/7/3 9:18
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DynamicControllerUtils {

    private final ApplicationContext applicationContext;
    private final RequestMappingHandlerMapping handlerMapping;
    private final SysScriptService scriptService;
    private final MultipleOpenApiResource multipleOpenApiResource;
    private final SpringDocProviders springDocProviders;

    private AnnotationConfigApplicationContext dynamicContext;
    private static final Map<String, Collection<RequestMappingInfo>> MAPPINGS = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        dynamicContext = new AnnotationConfigApplicationContext();
        dynamicContext.setParent(applicationContext);
        dynamicContext.refresh();
    }

    /**
     * 初始化動態(tài)controller
     */
    @EventListener(ApplicationReadyEvent.class)
    public void initDynamicController() {
        log.info("初始化動態(tài)controller");
        List<SysScript> list = scriptService.lambdaQuery().likeRight(SysScript::getType, "controller:").list();
        list.forEach(this::registerController);
    }

    @SuppressWarnings("unchecked")
    public void refresh(String scriptType) {
        String script = scriptService.getByType(scriptType);

        try {
            //刪除舊的bean
            dynamicContext.getDefaultListableBeanFactory().removeBeanDefinition(scriptType);

            //注冊新的bean
            Class<Object> type = GroovyUtils.loadClass(script);
            dynamicContext.registerBean(scriptType, type);
            Object bean = dynamicContext.getBean(scriptType);

            //注銷原有的controller
            unregister(scriptType);

            //重新注冊controller
            detectHandlerMethods(bean, scriptType);

            //刷新open api緩存,包括刷新openAPIService內(nèi)部的mappingsMap和springWebProvider內(nèi)部的handlerMethods
            OpenAPIService openAPIService = getOpenApiService();
            openAPIService.addMappings(Map.of(bean.toString(), bean));
            Optional<SpringWebProvider> springWebProvider = springDocProviders.getSpringWebProvider();
            if (springWebProvider.isPresent()) {
                Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
                springWebProvider.get().getHandlerMethods().putAll(handlerMethods);
            }

            // 反射獲取 openAPIService中的緩存
            Field cachedOpenAPIField = OpenAPIService.class.getDeclaredField("cachedOpenAPI");
            ReflectionUtils.makeAccessible(cachedOpenAPIField);
            Map<String, OpenAPI> cache = (Map<String, OpenAPI>) cachedOpenAPIField.get(openAPIService);
            cache.clear();
        } catch (Exception e) {
            throw new BaseException(e);
        }

    }

    /**
     * 注銷原有的controller接口
     *
     * @param type type
     */
    private void unregister(String type) {
        Collection<RequestMappingInfo> mappings = MAPPINGS.remove(type);
        if (Check.isEmpty(mappings)) {
            log.warn("未找到{}相關(guān)的映射", type);
            return;
        }

        for (RequestMappingInfo mapping : mappings) {
            handlerMapping.unregisterMapping(mapping);
            log.info("{} HTTP接口{}注銷成功", type, mapping);
        }
    }

    /**
     * 注冊controller到mapping,并添加到open api
     *
     * @param script 腳本
     */
    private void registerController(SysScript script) {
        String s = scriptService.getScript(script);
        Class<Object> type = GroovyUtils.loadClass(s);

        dynamicContext.registerBean(script.getType(), type);
        Object bean = dynamicContext.getBean(type);

        detectHandlerMethods(bean, script.getType());

        OpenAPIService openApiService = getOpenApiService();
        openApiService.addMappings(Map.of(bean.toString(), bean));
    }


    private OpenAPIService getOpenApiService() {
        try {
            //反射獲取openApiResource
            Method getOpenApiResource = MultipleOpenApiResource.class.getDeclaredMethod("getOpenApiResourceOrThrow", String.class);
            ReflectionUtils.makeAccessible(getOpenApiResource);
            OpenApiResource openApiResource = (OpenApiResource) getOpenApiResource.invoke(multipleOpenApiResource, "dynamic");

            // 反射獲取 openAPIService
            Field openAPIServiceField = AbstractOpenApiResource.class.getDeclaredField("openAPIService");
            ReflectionUtils.makeAccessible(openAPIServiceField);
            return (OpenAPIService) openAPIServiceField.get(openApiResource);
        } catch (Exception e) {
            throw new BaseException("獲取反射獲取openApiResource和openApiService失敗", e);
        }
    }

    /**
     * Look for handler methods in the specified handler bean.
     *
     * @param handler either a bean name or an actual handler instance
     * @param name
     */
    private void detectHandlerMethods(Object handler, String name) {
        Class<?> handlerType = handler.getClass();

        Class<?> userType = ClassUtils.getUserClass(handlerType);
        Map<Method, RequestMappingInfo> methods = MethodIntrospector.selectMethods(userType,
                (MethodIntrospector.MetadataLookup<RequestMappingInfo>) method -> getMappingForMethod(method, userType));

        MAPPINGS.put(name, methods.values());
        methods.forEach((method, mapping) -> {
            Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
            handlerMapping.registerMapping(mapping, handler, invocableMethod);
            log.info("接口{}注冊成功", mapping);
        });
    }


    private RequestMappingInfo getMappingForMethod(Method method, Class<?> userType) {
        try {
            Method getMappingForMethod = AbstractHandlerMethodMapping.class.getDeclaredMethod("getMappingForMethod", Method.class, Class.class);
            ReflectionUtils.makeAccessible(getMappingForMethod);
            return (RequestMappingInfo) getMappingForMethod.invoke(handlerMapping, method, userType);
        } catch (Exception e) {
            throw new BaseException("Invalid mapping on handler class [" + userType.getName() + "]: " + method, e);
        }
    }


}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 用兩張圖告訴你,為什么你的 App 會卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 14,000評論 2 59
  • 1.請簡單說明多線程技術(shù)的優(yōu)點和缺點? 優(yōu)點能適當(dāng)提高程序的執(zhí)行效率能適當(dāng)提高資源的利用率(CPU/內(nèi)存利用率) ...
    彼岸的黑色曼陀羅閱讀 549評論 0 2
  • 轉(zhuǎn)載:http://blog.csdn.net/u013263917/article/details/728957...
    Jonath閱讀 1,180評論 0 4
  • 前言2017年6月6日凌晨一點(北京時間),蘋果在2017WWDC大會上發(fā)布了全新的iOS11系統(tǒng)??赡艽蠹矣∠蟊?..
    Daimer閱讀 1,245評論 0 1
  • 轉(zhuǎn)載請標(biāo)注出處:www.itdecent.cn/p/1167d2ecd0ac:,以及版權(quán)歸屬黑馬程序員:http:...
    坤小閱讀 3,749評論 4 24

友情鏈接更多精彩內(nèi)容