Dubbo和Spring结合配置文件内容解析为bean的过程「建议收藏」

本篇讲解一下Dubbo中Bean的加载过程以及简单介绍Dubbo中服务的暴露和服务的引用!Dubbo是结合Spring来进行使用的,其中bean依赖Spring的IOC容器进行管理。Spring默认的Bean加载机制肯定是不能去加载Dubbo提供的Bean,那么Dubbo中的Bean是如何加载到Spring 容器的呢?

大家好,又见面了,我是全栈君。

Dubbo 现在已经被很多公司广泛的使用,Dubbo的使用和特性本篇不做讲解,本篇讲解一下Dubbo和Spring结合配置文件内容解析为bean的过程!

Dubbo是结合Spring来进行使用的,其中bean依赖Spring的IOC容器进行管理。Spring默认的Bean加载机制肯定是不能去加载Dubbo提供的Bean,那么Dubbo中的Bean是如何加载到Spring 容器的呢?下面进行介绍:

一、从Dubbo的配置说起

搭建一个Dubbo服务框架,Dubbo的配置文件必不可少。那么首先从Dubbo的配置文件applicationProvider.xml说起,看一个Dubbo的provide配置!

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">   

    <!-- 提供方应用信息,用于计算依赖关系 -->
    <dubbo:application name="dubbo_provider" />      
    <!-- 使用zookeeper注册中心暴露服务地址 -->  
    <dubbo:registry address="zookeeper://127.0.0.1:2181" />     
    <!-- 用dubbo协议在20880端口暴露服务 -->  
    <dubbo:protocol name="dubbo" port="20880" />  
    <!-- 声明需要暴露的服务接口 -->  
    <dubbo:service interface="com.dufy.service.ProviderService" ref="providerService"/>
     <!-- 具体的实现bean -->  
    <bean id="providerService" class="com.dufy.service.ProviderServiceImpl"/>
</beans> 

从配置文件内容中我们可以看出:

  1. 由于Spring提供了可扩展Schema的支持,Dubbo有自己的schema 文件!
    xmlns:dubbo=”http://code.alibabatech.com/schema/dubbo”指定Dubbo自定义Schema,xsi:schemaLocation用来指定xsd文件! XSD – < schema > 元素 -w3school
  2. Dubbo有一些自定义的标签,如
<dubbo:application
<dubbo:registry 
.....

二、Spring如何解析Dubbo的配置

1、加载Dubbo的配置文件

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(  
                new String[]{
  
  "applicationProvider.xml"}); 

Web项目,在web.xml中指定加载文件地址

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:application_*.xml</param-value>
</context-param>

Spring容器在启动的时候,会读取到Spring默认的一些schema以及Dubbo自定义的schema,每个schema都会对应一个自己的NamespaceHandler,NamespaceHandler里面通过BeanDefinitionParser来解析配置信息并转化为需要加载的bean对象!
下面通过分析ClassPathXmlApplicationContext 加载和解析applicationProvider.xml过程!

2、Spring加载Dubbo配置文件解析过程

AbstractXmlApplicationContext的loadBeanDefinitions方法中使用XmlBeanDefinitionReader. loadBeanDefinitions加载applicationProvider.xml文件

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
        Resource[] configResources = this.getConfigResources();
        if(configResources != null) {
            reader.loadBeanDefinitions(configResources);
        }

        String[] configLocations = this.getConfigLocations();
        if(configLocations != null) {
            reader.loadBeanDefinitions(configLocations);
            //configLocations = applicationProvider.xml
        }

    }

DefaultBeanDefinitionDocumentReader的parseBeanDefinitions方法中,对加载的applicationProvider.xm文件元素使用BeanDefinitionParserDelegate对象进行解析

 protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
        if(delegate.isDefaultNamespace(root)) {
  
  //是否是默认的NameSpace,Dubbo Namespace不是默认的
            NodeList nl = root.getChildNodes();
            for(int i = 0; i < nl.getLength(); ++i) {
                Node node = nl.item(i);
                if(node instanceof Element) {
                    Element ele = (Element)node;
                    if(delegate.isDefaultNamespace(ele)) {
                        this.parseDefaultElement(ele, delegate);
                    } else {
                        delegate.parseCustomElement(ele);
                    }
                }
            }
        } else {
        //通过代理来解析Dubbo配置文件中 Element 元素
            delegate.parseCustomElement(root);
        }

    }

进入BeanDefinitionParserDelegate 中的 parseCustomElement 方法中

public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
        //通过元素获取namespaceURI
        String namespaceUri = this.getNamespaceURI(ele);
        //如 ele:name 为 dubbo:application ,则namespaceUri = http://code.alibabatech.com/schema/dubbo
        //通过NameSpaceURi 获取NamespaceHandler ,Dubbo对应的是DubboNameSpaceHandler 
        NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver()
        .resolve(namespaceUri);//resolve解析请往下看
        if(handler == null) {
            this.error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
            return null;
        } else {
            //DubboBeanDefinitionParser的parse解析
            return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
        }
    }

调用resolve()方法,处理

 public NamespaceHandler resolve(String namespaceUri) {
         //此处Map为Spring需要加载的所有namespaceUri 对应的Handler
         //即 Map<namespaceUri ,handlerOrClassName >
        Map handlerMappings = this.getHandlerMappings();
        //这里因为namespaceUri 为Dubbo命名空间,故 Handler 为 DubboNamespaceHandler 
        Object handlerOrClassName = handlerMappings.get(namespaceUri);
        .....
        namespaceHandler.init();//调用init方法进行初始操作
        handlerMappings.put(namespaceUri, namespaceHandler);
        return namespaceHandler;
       .....

        }
    }

遇到dubbo名称空间 ,首先会调用DubboNamespaceHandler init 进行初始化操作,代码如下

public class DubboNamespaceHandler extends NamespaceHandlerSupport { 
   
    public DubboNamespaceHandler() {
    }

    public void init() {
        this.registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
        this.registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
        this.registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
        this.registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
        this.registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
        this.registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
        this.registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
        this.registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
        this.registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
        this.registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true));
    }
}

根据不同的XML节点,会委托NamespaceHandlerSupport找出合适的BeanDefinitionParser,其中Dubbo所有的标签都使用 DubboBeanDefinitionParser进行解析,基于一对一属性映射,将XML标签解析为Bean对象。

三:DubboBeanDefinitionParser解析过程简单介绍

由于DubboBeanDefinitionParser中 parse转换的过程代码还是比较复杂,只抽离出来bean的注册这一块的代码:

private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {

        RootBeanDefinition beanDefinition = new RootBeanDefinition();
        beanDefinition.setBeanClass(beanClass);
        beanDefinition.setLazyInit(false);
        String id = element.getAttribute("id");
        //省略......
         if(id != null && id.length() > 0) {
            if(parserContext.getRegistry().containsBeanDefinition(id)) {
                throw new IllegalStateException("Duplicate spring bean id " + id);
            }
            //registerBeanDefinition 注册Bean的定义
            //具体的id如下 applicationProvider.xml解析后的显示 id,
            //如id="dubbo_provider" beanDefinition = "ApplicationConfig"
            parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
            beanDefinition.getPropertyValues().addPropertyValue("id", id);
        }

     //省略.....

上面的applicationProvider.xml转换后大概是下面这个样子:

<!-- 提供方应用信息,用于计算依赖关系 -->
<bean id="dubbo_provider" class="com.alibaba.dubbo.config.ApplicationConfig"/>
<!-- 使用zookeeper注册中心暴露服务地址 -->
<bean id="registryConfig" class="com.alibaba.dubbo.config.RegistryConfig">
    <property name="address" value="127.0.0.1:2181"/>
    <property name="protocol" value="zookeeper"/>
</bean>
  <!-- 用dubbo协议在20880端口暴露服务 -->  
<bean id="dubbo" class="com.alibaba.dubbo.config.ProtocolConfig">
    <property name="port" value="20880"/>
</bean>
<!-- 声明需要暴露的服务接口 -->  
<bean id="com.dufy.service.ProviderService" class="com.alibaba.dubbo.config.spring.ServiceBean">
    <property name="interface" value="com.dufy.service.ProviderService"/>
    <property name="ref" ref="providerService"/>
</bean>
<bean id="providerService" class="com.dufy.service.ProviderServiceImpl" />

通过DubboBeanDefinitionParser的 parse会将class信息封装成BeanDefinition,然后将BeanDefinition再放进DefaultListableBeanFactory的beanDefinitionMap中。
最后通过Spring bean 的加载机制进行加载!


欢迎访问我的csdn博客,愿我们一同成长!

不管做什么,只要坚持下去就会看到不一样!在路上,不卑不亢!

博客首页http://blog.csdn.net/u010648555

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/121140.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • jax-ws java_通过JAX-WS实现WebService

    jax-ws java_通过JAX-WS实现WebService(一)服务端的创建一,首先创建一个Web项目,或者创建一个WebService项目也行(差别就是后者在开始就设置了WebService的调用方式)二,在项目中创建一个类作为我们要发布的服务(需要是非静态的public方法,我这里的main方法就是一个尝试)三,把这个项目转成一个WebService项目(开始就创建的WebService项目也要走这步),在划红线部分选择NewWebSe…

  • Angular面试题_angular面试

    Angular面试题_angular面试必看https://www.cnblogs.com/yugege/p/6526215.htmlangularjs是mvc还是mvvm框架?首先阐述下你对mvc和mvvm的理解首先为什么我们会需要MVC?因为随着代码规模越来越大,切分职责是大势所趋,还有为了后期维护方便,修改一块功能不影响其他功能。还有为了复用,因为很多逻辑是一样的。而MVC只是手段,终极目标是模块化和复用。mvvm的优点…

    2022年10月18日
  • kali更新源没有mysql_Kali更新源添加

    kali更新源没有mysql_Kali更新源添加    2.按键盘A进行对更新源的输入;3.常见的更新源如下:3.1中科大debhttp://mirrors.ustc.edu.cn/kalikali-rollingmainnon-freecontribdeb-srchttp://mirrors.ustc.edu.cn/kalikali-rollingmainnon-freecontrib3.2阿里云debhttp://m…

  • linux内核编程_linux内核是什么

    linux内核编程_linux内核是什么什么是操作系统?指在系统中负责完成最基本功能和系统管理的部分,操作系统有哪些组成部分?内核——操作系统的内在核心 设备驱动程序 启动引导程序 命令行shell 其他种类的用户界面—-操作系统的外在表象 基本的文件管理工具和系统工具Linux内核的组成Linux内核源代码目录结构是什么,各目录有什么含义?arch:包含和硬件体系结构相关的代码,每种平台占一…

  • Ubuntu 软件卸载[通俗易懂]

    Ubuntu 软件卸载[通俗易懂]1.卸载程序和所有配置文件。在终端中输入以下命令,卸载需要完全移除的程序:sudoapt-get–purgeremovesoftname2.只卸载程序。如果你移除程序但保留配置文件,请输入以下命令:sudoapt-getremovesoftname参考:Ubuntu16.04软件卸载-简书…

  • linux 查看文件系统类型「建议收藏」

    linux 查看文件系统类型「建议收藏」查看linux文件系统的方式有多种,一般通用的就mount和df。具体如下:目录mountdffileparted mount df file parted

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号