Dubbo Spring

Dubbo Spring 解析

dubbo的spi機(jī)制是如何管理dubbo的bean和如何進(jìn)行擴(kuò)展的基礎(chǔ)。那么dubbo是如何與spring進(jìn)行集成的呢?先來(lái)看一下官方的例子(在我的電腦上需要加上-Djava.net.preferIPv4Stack=true配置才能啟動(dòng)):

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">

    <dubbo:application name="demo-provider"/>

    <dubbo:registry address="multicast://224.5.6.7:1234"/>

    <dubbo:protocol name="dubbo" port="20880"/>

    <bean id="demoService" class="org.apache.dubbo.demo.provider.DemoServiceImpl"/>

    <dubbo:service interface="org.apache.dubbo.demo.DemoService" ref="demoService"/>

</beans>

可以看到很多都是dubbo自己定義的標(biāo)簽,那么這些標(biāo)簽定義在什么地方呢,beans中最后一行的配置給出了答案。此處通過(guò)spring的擴(kuò)展方案,在META-INF目錄下的spring.handlersspring.schemas兩個(gè)文件指定了dubbo的xsd文件和DubboNamespaceHandler命名空間解析器實(shí)現(xiàn)了擴(kuò)展。

DubboNamespaceHandler

public class DubboNamespaceHandler extends NamespaceHandlerSupport {
    //檢查是否有多個(gè)版本
    static {
        Version.checkDuplicate(DubboNamespaceHandler.class);
    }
    //對(duì)各個(gè)類型的標(biāo)簽解析成對(duì)應(yīng)類型的對(duì)象
    @Override
    public void init() {
        registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
        registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
        registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
        registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
        registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
        registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
        registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
        registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
        registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
        registerBeanDefinitionParser("annotation", new AnnotationBeanDefinitionParser());
    }

}

可以看到除了掃包配置,其他類型都是通過(guò)DubboBeanDefinitionParser這個(gè)類解析的。

BeanDefinitionParserDelegate

在分析DubboBeanDefinitionParser代碼前,有必要簡(jiǎn)單看一下解析器在Spring中是如何被調(diào)用的。

public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
    //找到對(duì)應(yīng)的beans標(biāo)簽中的uri
    String namespaceUri = getNamespaceURI(ele);
    //找到對(duì)應(yīng)的命名空間解析器
    NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
    if (handler == null) {
        error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
        return null;
    }
    //調(diào)用解析器解析,注意在DefaultNamespaceHandlerResolver類中已經(jīng)保證init方法被調(diào)用了
    return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}

DubboBeanDefinitionParser

這里僅貼出最重要的一部分代碼(其實(shí)這個(gè)類的代碼可以跳過(guò)),看一下是如何對(duì)xml標(biāo)簽處理的。

@SuppressWarnings("unchecked")
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
    //初始一個(gè)RootBeanDefinition
    RootBeanDefinition beanDefinition = new RootBeanDefinition();
    //設(shè)置class類型
    beanDefinition.setBeanClass(beanClass);
    //設(shè)置非延遲初始化
    beanDefinition.setLazyInit(false);
    //得到xml中定義的id
    String id = element.getAttribute("id");
    if ((id == null || id.length() == 0) && required) {
        //id不存在且必須就去拿name屬性
        String generatedBeanName = element.getAttribute("name");
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            //協(xié)議默認(rèn)為dubbo
            if (ProtocolConfig.class.equals(beanClass)) {
                generatedBeanName = "dubbo";
            } else {
                //默認(rèn)拿接口全類名
                generatedBeanName = element.getAttribute("interface");
            }
        }
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            //默認(rèn)拿接口全類名
            generatedBeanName = beanClass.getName();
        }
        id = generatedBeanName;
        int counter = 2;
        //已經(jīng)存在生產(chǎn)數(shù)字后綴,直到名字不存在
        while (parserContext.getRegistry().containsBeanDefinition(id)) {
            id = generatedBeanName + (counter++);
        }
    }
    if (id != null && id.length() > 0) {
        //id校驗(yàn)唯一
        if (parserContext.getRegistry().containsBeanDefinition(id)) {
            throw new IllegalStateException("Duplicate spring bean id " + id);
        }
        //注冊(cè)該對(duì)象
        parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
        //添加bean的id屬性
        beanDefinition.getPropertyValues().addPropertyValue("id", id);
    }
    //ProtocolConfig類型的特殊處理
    if (ProtocolConfig.class.equals(beanClass)) {
        //遍歷當(dāng)前spring容器內(nèi)所有的bean的所有解析的屬性
        for (String name : parserContext.getRegistry().getBeanDefinitionNames()) {
            BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name);
            PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol");
            if (property != null) {
                Object value = property.getValue();
                //如果其他BeanDefinition存在屬性值是ProtocolConfig類型并且協(xié)議名字一樣的那么添加屬性
                //這一步實(shí)現(xiàn)了類似ServiceConfig有protocol屬性的類型可以根據(jù)協(xié)議名字注入指定協(xié)議
                if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) {
                    definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id));
                }
            }
        }
        //ServiceBean特殊處理
    } else if (ServiceBean.class.equals(beanClass)) {
        //如果<dubbo:service>標(biāo)簽指定了className,那么自動(dòng)生成該對(duì)象,并還是通過(guò)ref引用
        String className = element.getAttribute("class");
        if (className != null && className.length() > 0) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(ReflectUtils.forName(className));
            classDefinition.setLazyInit(false);
            //解析屬性放到BeanDefinition
            parseProperties(element.getChildNodes(), classDefinition);
            beanDefinition.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl"));
        }
        //ProviderConfig和ConsumerConfig繼續(xù)掃描內(nèi)部的dubbo bean
    } else if (ProviderConfig.class.equals(beanClass)) {
        parseNested(element, parserContext, ServiceBean.class, true, "service", "provider", id, beanDefinition);
    } else if (ConsumerConfig.class.equals(beanClass)) {
        parseNested(element, parserContext, ReferenceBean.class, false, "reference", "consumer", id, beanDefinition);
    }
    Set<String> props = new HashSet<String>();
    ManagedMap parameters = null;
    for (Method setter : beanClass.getMethods()) {
        String name = setter.getName();
        //遍歷所有的set方法
        if (name.length() > 3 && name.startsWith("set")
                && Modifier.isPublic(setter.getModifiers())
                && setter.getParameterTypes().length == 1) {
            Class<?> type = setter.getParameterTypes()[0];
            //使用-隔開(kāi)駝峰命名的屬性
            String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-");
            props.add(property);
            //查找名字對(duì)應(yīng)的get方法
            Method getter = null;
            try {
                getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]);
            } catch (NoSuchMethodException e) {
                try {
                    getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]);
                } catch (NoSuchMethodException e2) {
                }
            }
            //是否有相應(yīng)的get方法
            if (getter == null
                    || !Modifier.isPublic(getter.getModifiers())
                    || !type.equals(getter.getReturnType())) {
                continue;
            }
            //有parameters參數(shù),對(duì)<dubbo:parameter>解析
            if ("parameters".equals(property)) {
                parameters = parseParameters(element.getChildNodes(), beanDefinition);
                //有parameters參數(shù),對(duì)<dubbo:method>解析
            } else if ("methods".equals(property)) {
                parseMethods(id, element.getChildNodes(), beanDefinition, parserContext);
                //argument解析
            } else if ("arguments".equals(property)) {
                parseArguments(id, element.getChildNodes(), beanDefinition, parserContext);
            } else {
                String value = element.getAttribute(property);
                if (value != null) {
                    value = value.trim();
                    if (value.length() > 0) {
                        //不設(shè)置注冊(cè)中心
                        if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) {
                            RegistryConfig registryConfig = new RegistryConfig();
                            registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
                            beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig);
                            //,隔開(kāi)的多注冊(cè)中心
                        } else if ("registry".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("registries", value, beanDefinition, parserContext);
                            //多provider提供方配置,隔開(kāi)
                        } else if ("provider".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("providers", value, beanDefinition, parserContext);
                            //多協(xié)議配置,隔開(kāi)
                        } else if ("protocol".equals(property) && value.indexOf(',') != -1) {
                            parseMultiRef("protocols", value, beanDefinition, parserContext);
                        } else {
                            Object reference;
                            if (isPrimitive(type)) {
                                //一些舊屬性選項(xiàng)的兼容,可以看到應(yīng)該都是取消的意思
                                if ("async".equals(property) && "false".equals(value)
                                        || "timeout".equals(property) && "0".equals(value)
                                        || "delay".equals(property) && "0".equals(value)
                                        || "version".equals(property) && "0.0.0".equals(value)
                                        || "stat".equals(property) && "-1".equals(value)
                                        || "reliable".equals(property) && "false".equals(value)) {
                                    value = null;
                                }
                                reference = value;
                            } else if ("protocol".equals(property)
                                    //spi存在該協(xié)議,保證可以加載
                                    && ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value)
                                    //spring容器內(nèi)沒(méi)有該名字對(duì)象或者類型不是協(xié)議配置
                                    && (!parserContext.getRegistry().containsBeanDefinition(value)
                                    || !ProtocolConfig.class.getName().equals(parserContext.getRegistry().getBeanDefinition(value).getBeanClassName()))) {
                                if ("dubbo:provider".equals(element.getTagName())) {
                                    logger.warn("Recommended replace <dubbo:provider protocol=\"" + value + "\" ... /> to <dubbo:protocol name=\"" + value + "\" ... />");
                                }
                                //這里對(duì)應(yīng)上面protocol屬性注入
                                ProtocolConfig protocol = new ProtocolConfig();
                                protocol.setName(value);
                                reference = protocol;
                                //返回回調(diào)
                            } else if ("onreturn".equals(property)) {
                                int index = value.lastIndexOf(".");
                                //對(duì)象引用
                                String returnRef = value.substring(0, index);
                                //回調(diào)方法
                                String returnMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(returnRef);
                                beanDefinition.getPropertyValues().addPropertyValue("onreturnMethod", returnMethod);
                                //異?;卣{(diào)
                            } else if ("onthrow".equals(property)) {
                                int index = value.lastIndexOf(".");
                                String throwRef = value.substring(0, index);
                                String throwMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(throwRef);
                                beanDefinition.getPropertyValues().addPropertyValue("onthrowMethod", throwMethod);
                                //調(diào)用前回調(diào)
                            } else if ("oninvoke".equals(property)) {
                                int index = value.lastIndexOf(".");
                                String invokeRef = value.substring(0, index);
                                String invokeRefMethod = value.substring(index + 1);
                                reference = new RuntimeBeanReference(invokeRef);
                                beanDefinition.getPropertyValues().addPropertyValue("oninvokeMethod", invokeRefMethod);
                            } else {
                                //引用對(duì)象
                                if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) {
                                    BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
                                    //單例
                                    if (!refBean.isSingleton()) {
                                        throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value + "\" scope=\"singleton\" ...>");
                                    }
                                }
                                reference = new RuntimeBeanReference(value);
                            }
                            //將解析的屬性放入PropertyValues
                            beanDefinition.getPropertyValues().addPropertyValue(property, reference);
                        }
                    }
                }
            }
        }
    }
    //解析參數(shù)map
    NamedNodeMap attributes = element.getAttributes();
    int len = attributes.getLength();
    for (int i = 0; i < len; i++) {
        Node node = attributes.item(i);
        String name = node.getLocalName();
        if (!props.contains(name)) {
            if (parameters == null) {
                parameters = new ManagedMap();
            }
            String value = node.getNodeValue();
            parameters.put(name, new TypedStringValue(value, String.class));
        }
    }
    if (parameters != null) {
        beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters);
    }
    return beanDefinition;
}

這里的解析大概了解了一下,感覺(jué)理解的還不是很到位,不過(guò)也不是很重要,對(duì)照著官方的使用說(shuō)明其實(shí)一看就七七八八了。

AnnotationBeanDefinitionParser

public class AnnotationBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {

    @Override
    protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
        //解析包路徑,支持,分隔
        String packageToScan = element.getAttribute("package");
        String[] packagesToScan = trimArrayElements(commaDelimitedListToStringArray(packageToScan));
        //放入ServiceAnnotationBeanPostProcessor的構(gòu)造入?yún)?        builder.addConstructorArgValue(packagesToScan);
        //bean級(jí)別,不是很理解這個(gè)的用處
        builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

        //注冊(cè)ReferenceAnnotationBeanPostProcessor處理Reference注解
        registerReferenceAnnotationBeanPostProcessor(parserContext.getRegistry());

    }
    //沒(méi)有注定id屬性就自動(dòng)生成
    @Override
    protected boolean shouldGenerateIdAsFallback() {
        return true;
    }

    private void registerReferenceAnnotationBeanPostProcessor(BeanDefinitionRegistry registry) {
        //注冊(cè)ReferenceAnnotationBeanPostProcessor處理Reference注解
        BeanRegistrar.registerInfrastructureBean(registry,
                ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class);

    }
    //注冊(cè)ServiceAnnotationBeanPostProcessor類型的對(duì)象
    @Override
    protected Class<?> getBeanClass(Element element) {
        return ServiceAnnotationBeanPostProcessor.class;
    }

}

這里就是注冊(cè)了ReferenceAnnotationBeanPostProcessorServiceAnnotationBeanPostProcessor兩個(gè)對(duì)象。其中ServiceAnnotationBeanPostProcessor實(shí)現(xiàn)了BeanFactoryPostProcessor接口,指定掃包路徑掃描Service注解生成ServiceBean。ReferenceAnnotationBeanPostProcessor實(shí)現(xiàn)了BeanPostProcessor掃描所有bean的Referenece注解的屬性生成ReferenceBean。至于實(shí)現(xiàn)的這兩個(gè)接口是如何工作的,可以查看spring的源碼,這是spring提供的一個(gè)擴(kuò)展方式。

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

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

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,612評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,275評(píng)論 6 342
  • 1.1 Spring IoC容器和bean簡(jiǎn)介 本章介紹了Spring Framework實(shí)現(xiàn)的控制反轉(zhuǎn)(IoC)...
    起名真是難閱讀 2,674評(píng)論 0 8
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,943評(píng)論 1 92
  • 1.1 spring IoC容器和beans的簡(jiǎn)介 Spring 框架的最核心基礎(chǔ)的功能是IoC(控制反轉(zhuǎn))容器,...
    simoscode閱讀 6,851評(píng)論 2 22

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