Dubbo原始碼學習筆記(配置初始化)
阿新 • • 發佈:2019-02-16
一、spring初始化時為什麼可以解析dubbo的配置?
dubbo基於Spring可擴充套件Schema提供自定義配置支援。dubbo是依賴spring提供的這種機制來處理配置檔案解析的,首先找到dubbo.jar下的META-INF/spring.handlers配置,內容如下:
http\://code.alibabatech.com/schema/dubbo=com.alibaba.dubbo.config.spring.schema.DubboNamespaceHandler也就是說我們在dubbo的xml配置標頭檔案中配置的這個xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"指向的是哪個具體的類,通過這個類作為入口來對此xml中對應的dubbo配置內容進行解析並初始化,spring對xml的配置解析不在此篇範疇。
二、DubboNamespaceHandler這個入口類都做了些什麼?
import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * DubboNamespaceHandler 此類繼承自spring的xml解析名稱空間處理類,只是簡單的一個init方法引用公共類進行 * * @author william.liangf * @export */ public class DubboNamespaceHandler extends NamespaceHandlerSupport { static { Version.checkDuplicate(DubboNamespaceHandler.class); } public void init() { /*最後將定義好的bean裝入到spring的bean容器中進行管理 */ 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 DubboBeanDefinitionParser(AnnotationBean.class, true)); } }
三、DubboBeanDefinitionParser公共類進行解讀,主要講述parse方法
以上是dubbo的xml中配置的屬性解析並轉換為bean的操作,這裡暫不涉及服務的暴露註冊以及服務的消費訂閱,細心的可能發現/* *DubboBeanDefinitionParser implements BeanDefinitionParser的parse方法,原始碼如下: */ public BeanDefinition parse(Element element, ParserContext parserContext) { /*直接呼叫本類中的一個靜態方法,進行xml元素轉換為bean的操作*/ return parse(element, parserContext, beanClass, required); } /*這裡需要注意的是,本類並不負責xml的讀取以及節點等內容的轉換,如果需要知道xml是怎麼被讀取以及操作的,可以沿著ParserContext找XmlBeanDefinitionReader以及相關的Resource介面實現類來進行了解*/ private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) { /*首先建立一個spring中的RootBeanDefinition物件,此物件繼承自spring中的AbstractBeanDefinition,這也是spring中對xml中bean定義解析的核心類*/ RootBeanDefinition beanDefinition = new RootBeanDefinition(); /*將DubboNamespaceHandler類中傳入的類名設定*/ beanDefinition.setBeanClass(beanClass); /*將DubboNamespaceHandler類中傳入的boolean值設定是否懶載入*/ beanDefinition.setLazyInit(false); String id = element.getAttribute("id"); /*不存在id屬性,並且是懶載入的*/ if ((id == null || id.length() == 0) && required) { String generatedBeanName = element.getAttribute("name"); if (generatedBeanName == null || generatedBeanName.length() == 0) { if (ProtocolConfig.class.equals(beanClass)) { generatedBeanName = "dubbo"; } else { generatedBeanName = element.getAttribute("interface"); } } if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = beanClass.getName(); } id = generatedBeanName; int counter = 2; while (parserContext.getRegistry().containsBeanDefinition(id)) { id = generatedBeanName + (counter++); } } /*存在id屬性,並且從已註冊的bean中比對是否存在相同名稱,是的話則丟擲異常,不相同則進行註冊*/ if (id != null && id.length() > 0) { if (parserContext.getRegistry().containsBeanDefinition(id)) { throw new IllegalStateException("Duplicate spring bean id " + id); } parserContext.getRegistry().registerBeanDefinition(id, beanDefinition); beanDefinition.getPropertyValues().addPropertyValue("id", id); } /*如果是協議配置類*/ if (ProtocolConfig.class.equals(beanClass)) { 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(); if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) { definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id)); } } } /*如果是暴露服務配置類*/ } else if (ServiceBean.class.equals(beanClass)) { String className = element.getAttribute("class"); if (className != null && className.length() > 0) { RootBeanDefinition classDefinition = new RootBeanDefinition(); classDefinition.setBeanClass(ReflectUtils.forName(className)); classDefinition.setLazyInit(false); parseProperties(element.getChildNodes(), classDefinition); beanDefinition.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl")); } /*如果是服務提供者配置類*/ } 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; /*接下來就是對各個配置類的屬性進行校驗以及呼叫set,get方法封裝了*/ for (Method setter : beanClass.getMethods()) { String name = setter.getName(); /*如果是public型別的set方法,如果這裡getName拿到的是get***則不處理接著迴圈*/ if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(setter.getModifiers()) && setter.getParameterTypes().length == 1) { Class<?> type = setter.getParameterTypes()[0]; /*對set方法的屬性名稱進行轉換,讓其都轉換為小寫字母,如果其中有駝峰命名的則使用中橫線連線,如:setNaMe 則會變成na-me*/ String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-"); props.add(property); Method getter = null; try { /*有沒有get方法,有的話會取到get方法的全限定名,比如ApplicationConfig.class有個getName,那麼得到整體為public java.lang.String com.alibaba.dubbo.config.ApplicationConfig.getName()*/ getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]); } catch (NoSuchMethodException e) { try { /*如果報錯了,再試下是否為boolean型別的方法*/ getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]); } catch (NoSuchMethodException e2) { } } /*如果不是public方法也不是,也不是get方法,同時set方法屬性型別與get方法返回值型別不一致,就不往下執行了*/ if (getter == null || !Modifier.isPublic(getter.getModifiers()) || !type.equals(getter.getReturnType())) { continue; } /*下面就是對屬性名稱一一的匹配,區分開特殊的bean*/ if ("parameters".equals(property)) { /*遍歷子節點集合的key,value裝入map中,key,value都封裝為string型別*/ parameters = parseParameters(element.getChildNodes(), beanDefinition); } else if ("methods".equals(property)) { /*遍歷方法標籤子節點,進行深層次再次封裝,方法名稱不能為null,否則將會丟擲throw new IllegalStateException("<dubbo:method> name attribute == null");異常*/ parseMethods(id, element.getChildNodes(), beanDefinition, parserContext); } 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) { /*如果屬性名稱為registry,值為N/A。則手動建立一個registryConfig,並設定為N/A表示服務不註冊*/ if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress(RegistryConfig.NO_AVAILABLE); beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig); /*如果屬性名稱為registry,值又是逗號分隔的多個*/ } else if ("registry".equals(property) && value.indexOf(',') != -1) { parseMultiRef("registries", value, beanDefinition, parserContext); /*如果屬性名稱為provider,值又是逗號分隔的多個*/ } else if ("provider".equals(property) && value.indexOf(',') != -1) { parseMultiRef("providers", value, beanDefinition, parserContext); /*如果屬性名稱為protocol,值又是逗號分隔的多個*/ } else if ("protocol".equals(property) && value.indexOf(',') != -1) { parseMultiRef("protocols", value, beanDefinition, parserContext); } else { Object reference; if (isPrimitive(type)) { 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)) { /* 鍏煎鏃х増鏈瑇sd涓殑default鍊�*/ value = null; } reference = value; } else if ("protocol".equals(property) && ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value) && (!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 + "\" ... />"); } /* 鍏煎鏃х増鏈厤緗�*/ ProtocolConfig protocol = new ProtocolConfig(); protocol.setName(value); reference = protocol; } else if ("onreturn".equals(property)) { int index = value.lastIndexOf("."); String returnRef = value.substring(0, index); String returnMethod = value.substring(index + 1); reference = new RuntimeBeanReference(returnRef); beanDefinition.getPropertyValues().addPropertyValue("onreturnMethod", returnMethod); } 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); } else { 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); } beanDefinition.getPropertyValues().addPropertyValue(property, reference); } } } } } } 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)); } } /*最後將封裝好的屬性map,都繫結給對應的bean*/ if (parameters != null) { beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters); } /*最後返回這個定義好的bean*/ return beanDefinition; }
在DubboNamespaceHandler入口中,針對parse的入參最下面幾個服務提供方,服務消費方以及註解都是通過子類的繼承來實現功能的擴充套件。