Dubbo Spring 解析
dubbo的spi机制是如何管理dubbo的bean和如何进行扩展的基础。那么dubbo是如何与spring进行集成的呢?先来看一下官方的例子(在我的电脑上需要加上-Djava.net.preferIPv4Stack=true
配置才能启动):
<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自己定义的标签,那么这些标签定义在什么地方呢,beans
中最后一行的配置给出了答案。此处通过spring的扩展方案,在META-INF
目录下的spring.handlers
和spring.schemas
两个文件指定了dubbo的xsd文件和DubboNamespaceHandler
命名空间解析器实现了扩展。
DubboNamespaceHandler
public class DubboNamespaceHandler extends NamespaceHandlerSupport {
//检查是否有多个版本
static {
Version.checkDuplicate(DubboNamespaceHandler.class);
}
//对各个类型的标签解析成对应类型的对象
@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());
}
}
可以看到除了扫包配置,其他类型都是通过DubboBeanDefinitionParser
这个类解析的。
BeanDefinitionParserDelegate
在分析DubboBeanDefinitionParser
代码前,有必要简单看一下解析器在Spring中是如何被调用的。
public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
//找到对应的beans标签中的uri
String namespaceUri = getNamespaceURI(ele);
//找到对应的命名空间解析器
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
if (handler == null) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
return null;
}
//调用解析器解析,注意在DefaultNamespaceHandlerResolver类中已经保证init方法被调用了
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}
DubboBeanDefinitionParser
这里仅贴出最重要的一部分代码(其实这个类的代码可以跳过),看一下是如何对xml标签处理的。
@SuppressWarnings("unchecked")
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
//初始一个RootBeanDefinition
RootBeanDefinition beanDefinition = new RootBeanDefinition();
//设置class类型
beanDefinition.setBeanClass(beanClass);
//设置非延迟初始化
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) {
//协议默认为dubbo
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++);
}
}
if (id != null && id.length() > 0) {
//id校验唯一
if (parserContext.getRegistry().containsBeanDefinition(id)) {
throw new IllegalStateException("Duplicate spring bean id " + id);
}
//注册该对象
parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
//添加bean的id属性
beanDefinition.getPropertyValues().addPropertyValue("id", id);
}
//ProtocolConfig类型的特殊处理
if (ProtocolConfig.class.equals(beanClass)) {
//遍历当前spring容器内所有的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类型并且协议名字一样的那么添加属性
//这一步实现了类似ServiceConfig有protocol属性的类型可以根据协议名字注入指定协议
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>标签指定了className,那么自动生成该对象,并还是通过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继续扫描内部的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];
//使用-隔开驼峰命名的属性
String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-");
props.add(property);
//查找名字对应的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) {
}
}
//是否有相应的get方法
if (getter == null
|| !Modifier.isPublic(getter.getModifiers())
|| !type.equals(getter.getReturnType())) {
continue;
}
//有parameters参数,对<dubbo:parameter>解析
if ("parameters".equals(property)) {
parameters = parseParameters(element.getChildNodes(), beanDefinition);
//有parameters参数,对<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) {
//不设置注册中心
if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
beanDefinition.getPropertyValues().addPropertyValue(property, registryConfig);
//,隔开的多注册中心
} 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);
//多协议配置,隔开
} 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)) {
value = null;
}
reference = value;
} else if ("protocol".equals(property)
//spi存在该协议,保证可以加载
&& ExtensionLoader.getExtensionLoader(Protocol.class).hasExtension(value)
//spring容器内没有该名字对象或者类型不是协议配置
&& (!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 + "\" ... />");
}
//这里对应上面protocol属性注入
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 ("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 {
//引用对象
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);
}
}
}
}
}
}
//解析参数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;
}
这里的解析大概了解了一下,感觉理解的还不是很到位,不过也不是很重要,对照着官方的使用说明其实一看就七七八八了。
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的构造入参
builder.addConstructorArgValue(packagesToScan);
//bean级别,不是很理解这个的用处
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
//注册ReferenceAnnotationBeanPostProcessor处理Reference注解
registerReferenceAnnotationBeanPostProcessor(parserContext.getRegistry());
}
//没有注定id属性就自动生成
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
private void registerReferenceAnnotationBeanPostProcessor(BeanDefinitionRegistry registry) {
//注册ReferenceAnnotationBeanPostProcessor处理Reference注解
BeanRegistrar.registerInfrastructureBean(registry,
ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class);
}
//注册ServiceAnnotationBeanPostProcessor类型的对象
@Override
protected Class<?> getBeanClass(Element element) {
return ServiceAnnotationBeanPostProcessor.class;
}
}
这里就是注册了ReferenceAnnotationBeanPostProcessor
和ServiceAnnotationBeanPostProcessor
两个对象。其中ServiceAnnotationBeanPostProcessor
实现了BeanFactoryPostProcessor
接口,指定扫包路径扫描Service
注解生成ServiceBean
。ReferenceAnnotationBeanPostProcessor
实现了BeanPostProcessor
扫描所有bean的Referenece
注解的属性生成ReferenceBean
。至于实现的这两个接口是如何工作的,可以查看spring的源码,这是spring提供的一个扩展方式。