dubbo-spring|dubbo学习篇1 注解之 @Reference 原理解析

一. 使用注解
在dubbo springboot 使用时,在需要调用的服务接口上使用 @Reference 即可直接调用远程服务

@Reference(version = "1.0.0", application = "${dubbo.application.id}") private HelloService helloService;

比如上述样式 调试发现调用时 helloSevice为一个生产的代理对象如下图:

二.分析原理
@Reference 的行为跟 @Autowired 类似 均实现了自动注入的过程 。
【dubbo-spring|dubbo学习篇1 注解之 @Reference 原理解析】首先参考下https://blog.csdn.net/qq_27529917/article/details/78454912 学习 @Autowired 工作原理 ,可跳过。
@Reference 的注解处理依赖于 ReferenceAnnotationBeanPostProcessor 类 该类的定义如下:
public class ReferenceAnnotationBeanPostProcessor extends AnnotationInjectedBeanPostProcessor implements ApplicationContextAware, ApplicationListener {/** * The bean name of {@link ReferenceAnnotationBeanPostProcessor} */ public static final String BEAN_NAME = "referenceAnnotationBeanPostProcessor"; /** * Cache size */ private static final int CACHE_SIZE = Integer.getInteger(BEAN_NAME + ".cache.size", 32); private final ConcurrentMap> referenceBeanCache = new ConcurrentHashMap<>(CACHE_SIZE); private final ConcurrentHashMap localReferenceBeanInvocationHandlerCache = new ConcurrentHashMap<>(CACHE_SIZE); private final ConcurrentMap> injectedFieldReferenceBeanCache = new ConcurrentHashMap<>(CACHE_SIZE); private final ConcurrentMap> injectedMethodReferenceBeanCache = new ConcurrentHashMap<>(CACHE_SIZE); private ApplicationContext applicationContext;

其中 referenceBeanCache缓存了接口对应bean的定义 localReferenceBeanInvocationHandlerCache缓存了接口对应InvocationHandler的定义。
参考 autowired的解析过程 分析首先找到 (2.63定义在当前类 原理一致)
class AnnotationInjectedBeanPostProcessor{@Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { if (beanType != null) { InjectionMetadata metadata = https://www.it610.com/article/findInjectionMetadata(beanName, beanType, null); metadata.checkConfigMembers(beanDefinition); } }}

执行的时间节点是bean刚刚初始化完 但在属性填充之前, spring会为每个beanDefinition依次调用实现了 MergedBeanDefinitionPostProcessor接口的PostProcessor的改方法(注册过程单独放在spring boot 自动配置章节)
该函数依次处理spring传来的beanClass 并解析class field method尝试找到
private List findFieldReferenceMetadata(Class beanClass) { final List elements = new LinkedList(); ReflectionUtils.doWithFields(beanClass, new FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { Reference reference = (Reference)AnnotationUtils.getAnnotation(field, Reference.class); if (reference != null) { if (Modifier.isStatic(field.getModifiers())) { if (ReferenceAnnotationBeanPostProcessor.this.logger.isWarnEnabled()) { ReferenceAnnotationBeanPostProcessor.this.logger.warn("@Reference annotation is not supported on static fields: " + field); }return; }elements.add(ReferenceAnnotationBeanPostProcessor.this.new ReferenceFieldElement(field, reference)); }} }); return elements; }

有这个定义的filed或者method 如果存在的话 就建立类定义中对应field method的缓存。同时加入到beanclass/beanname对应该meta信息的缓存 以便同样的请求过来不在解析。
之后 处理调用该函数
public void checkConfigMembers(RootBeanDefinition beanDefinition) { Set checkedElements = new LinkedHashSet(this.injectedElements.size()); Iterator var3 = this.injectedElements.iterator(); while(var3.hasNext()) { InjectionMetadata.InjectedElement element = (InjectionMetadata.InjectedElement)var3.next(); Member member = element.getMember(); if (!beanDefinition.isExternallyManagedConfigMember(member)) { beanDefinition.registerExternallyManagedConfigMember(member); checkedElements.add(element); if (logger.isDebugEnabled()) { logger.debug("Registered injected element on class [" + this.targetClass.getName() + "]: " + element); } } }this.checkedElements = checkedElements; }

这个函数会将上个函数标注出来需要被注入的域标注为"外部管理",只有被标注为外部管理的成员 在后续才会在当前bean实例化调用postProcessPropertyValues来处理外部注入
最后一步 postProcessPropertyValues 注入属性

public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException { InjectionMetadata metadata = https://www.it610.com/article/this.findReferenceMetadata(beanName, bean.getClass(), pvs); try { metadata.inject(bean, beanName, pvs); return pvs; } catch (BeanCreationException var7) { throw var7; } catch (Throwable var8) { throw new BeanCreationException(beanName,"Injection of @Reference dependencies failed", var8); } }public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { Collection checkedElements = this.checkedElements; Collection elementsToIterate = checkedElements != null ? checkedElements : this.injectedElements; if (!((Collection)elementsToIterate).isEmpty()) { boolean debug = logger.isDebugEnabled(); InjectionMetadata.InjectedElement element; for(Iterator var7 = ((Collection)elementsToIterate).iterator(); var7.hasNext(); element.inject(target, beanName, pvs)) { element = (InjectionMetadata.InjectedElement)var7.next(); if (debug) { logger.debug("Processing injected element of bean '" + beanName + "': " + element); } } }}

具体过程为判断当前bean 是否需要当前的processor注入 如果需要的话 即执行注入
protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs) throws Throwable { if (this.isField) { Field field = (Field)this.member; ReflectionUtils.makeAccessible(field); field.set(target, this.getResourceToInject(target, requestingBeanName)); } else { if (this.checkPropertySkipping(pvs)) { return; }try { Method method = (Method)this.member; ReflectionUtils.makeAccessible(method); method.invoke(target, this.getResourceToInject(target, requestingBeanName)); } catch (InvocationTargetException var5) { throw var5.getTargetException(); } }}

其中 本实例中实际处理inject动作的为
private class ReferenceFieldElement extends InjectedElement protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { Class referenceClass = this.field.getType(); this.referenceBean = ReferenceAnnotationBeanPostProcessor.this.buildReferenceBean(this.reference, referenceClass); ReflectionUtils.makeAccessible(this.field); this.field.set(bean, this.referenceBean.getObject()); }

其中具体的创建代码为
private ReferenceBean buildReferenceBean(Reference reference, Class referenceClass) throws Exception { String referenceBeanCacheKey = this.generateReferenceBeanCacheKey(reference, referenceClass); ReferenceBean referenceBean = (ReferenceBean)this.referenceBeansCache.get(referenceBeanCacheKey); if (referenceBean == null) { ReferenceBeanBuilder beanBuilder = (ReferenceBeanBuilder)ReferenceBeanBuilder.create(reference, this.classLoader, this.applicationContext).interfaceClass(referenceClass); referenceBean = (ReferenceBean)beanBuilder.build(); this.referenceBeansCache.putIfAbsent(referenceBeanCacheKey, referenceBean); }return referenceBean; }

该过程生成了一个referencebean的实例 并根据注解参数配置了
public class ReferenceBean extends ReferenceConfig

ReferenceConfig的参数。

此时执行最后一步
this.field.set(bean, this.referenceBean.getObject());

此时尝试去当前referenceBean去除绑定的 dubbo调用invoke对象 如果不存在则创建一个
具体创建过程比较长
private void init() { // 构建参数map this.ref = this.createProxy(map); }

最终创建动态代理 并将ref对象赋值给@Reference注解的成员 。
完。

    推荐阅读