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

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

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.reibang.com/u/aba665c4151f">簡(jiǎn)書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();
    }

    /**
     * 初始化動(dòng)態(tài)controller
     */
    @EventListener(ApplicationReadyEvent.class)
    public void initDynamicController() {
        log.info("初始化動(dòng)態(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);

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

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

            //重新注冊(cè)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);
        }
    }

    /**
     * 注冊(cè)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("接口{}注冊(cè)成功", 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)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市实苞,隨后出現(xiàn)的幾起案子剪廉,更是在濱河造成了極大的恐慌,老刑警劉巖朴肺,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件窖剑,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡戈稿,警方通過查閱死者的電腦和手機(jī)西土,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鞍盗,“玉大人需了,你說我怎么就攤上這事“慵祝” “怎么了肋乍?”我有些...
    開封第一講書人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)欣除。 經(jīng)常有香客問我住拭,道長(zhǎng),這世上最難降的妖魔是什么历帚? 我笑而不...
    開封第一講書人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任滔岳,我火速辦了婚禮,結(jié)果婚禮上挽牢,老公的妹妹穿的比我還像新娘谱煤。我一直安慰自己,他們只是感情好禽拔,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開白布刘离。 她就那樣靜靜地躺著,像睡著了一般睹栖。 火紅的嫁衣襯著肌膚如雪硫惕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評(píng)論 1 302
  • 那天野来,我揣著相機(jī)與錄音恼除,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛豁辉,可吹牛的內(nèi)容都是我干的令野。 我是一名探鬼主播,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼徽级,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼气破!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起餐抢,我...
    開封第一講書人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤现使,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后弹澎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體朴下,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡努咐,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年苦蒿,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片渗稍。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡佩迟,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出竿屹,到底是詐尸還是另有隱情报强,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布拱燃,位于F島的核電站秉溉,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏碗誉。R本人自食惡果不足惜召嘶,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望哮缺。 院中可真熱鬧弄跌,春花似錦、人聲如沸尝苇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽糠溜。三九已至淳玩,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間非竿,已是汗流浹背蜕着。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留汽馋,地道東北人侮东。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓圈盔,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親悄雅。 傳聞我的和親對(duì)象是個(gè)殘疾皇子驱敲,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 用兩張圖告訴你,為什么你的 App 會(huì)卡頓? - Android - 掘金 Cover 有什么料宽闲? 從這篇文章中你...
    hw1212閱讀 12,723評(píng)論 2 59
  • 1.請(qǐng)簡(jiǎn)單說明多線程技術(shù)的優(yōu)點(diǎn)和缺點(diǎn)众眨? 優(yōu)點(diǎn)能適當(dāng)提高程序的執(zhí)行效率能適當(dāng)提高資源的利用率(CPU/內(nèi)存利用率) ...
    彼岸的黑色曼陀羅閱讀 461評(píng)論 0 2
  • 轉(zhuǎn)載:http://blog.csdn.net/u013263917/article/details/728957...
    Jonath閱讀 1,136評(píng)論 0 4
  • 前言2017年6月6日凌晨一點(diǎn)(北京時(shí)間),蘋果在2017WWDC大會(huì)上發(fā)布了全新的iOS11系統(tǒng)容诬∶淅妫可能大家印象比...
    Daimer閱讀 1,084評(píng)論 0 1
  • 轉(zhuǎn)載請(qǐng)標(biāo)注出處:www.reibang.com/p/1167d2ecd0ac:,以及版權(quán)歸屬黑馬程序員:http:...
    坤小閱讀 3,650評(píng)論 4 24