当前位置:   article > 正文

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

@reference

一. 使用注解

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

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

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

 

二.分析原理

@Reference 的行为跟 @Autowired 类似 均实现了自动注入的过程 。

首先参考下https://blog.csdn.net/qq_27529917/article/details/78454912 学习 @Autowired 工作原理 ,可跳过。

@Reference 的注解处理依赖于 ReferenceAnnotationBeanPostProcessor 类 该类的定义如下:

  1. public class ReferenceAnnotationBeanPostProcessor extends AnnotationInjectedBeanPostProcessor implements
  2. ApplicationContextAware, ApplicationListener {
  3. /**
  4. * The bean name of {@link ReferenceAnnotationBeanPostProcessor}
  5. */
  6. public static final String BEAN_NAME = "referenceAnnotationBeanPostProcessor";
  7. /**
  8. * Cache size
  9. */
  10. private static final int CACHE_SIZE = Integer.getInteger(BEAN_NAME + ".cache.size", 32);
  11. private final ConcurrentMap<String, ReferenceBean<?>> referenceBeanCache =
  12. new ConcurrentHashMap<>(CACHE_SIZE);
  13. private final ConcurrentHashMap<String, ReferenceBeanInvocationHandler> localReferenceBeanInvocationHandlerCache =
  14. new ConcurrentHashMap<>(CACHE_SIZE);
  15. private final ConcurrentMap<InjectionMetadata.InjectedElement, ReferenceBean<?>> injectedFieldReferenceBeanCache =
  16. new ConcurrentHashMap<>(CACHE_SIZE);
  17. private final ConcurrentMap<InjectionMetadata.InjectedElement, ReferenceBean<?>> injectedMethodReferenceBeanCache =
  18. new ConcurrentHashMap<>(CACHE_SIZE);
  19. private ApplicationContext applicationContext;

其中 referenceBeanCache缓存了接口对应bean的定义 localReferenceBeanInvocationHandlerCache缓存了接口对应InvocationHandler的定义。

参考 autowired的解析过程 分析首先找到 (2.63定义在当前类 原理一致)

  1. class AnnotationInjectedBeanPostProcessor{
  2. @Override
  3. public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
  4. if (beanType != null) {
  5. InjectionMetadata metadata = findInjectionMetadata(beanName, beanType, null);
  6. metadata.checkConfigMembers(beanDefinition);
  7. }
  8. }
  9. }

执行的时间节点是bean刚刚初始化完 但在属性填充之前, spring会为每个beanDefinition依次调用实现了 MergedBeanDefinitionPostProcessor接口的PostProcessor的改方法(注册过程单独放在spring boot 自动配置章节)

该函数依次处理spring传来的beanClass 并解析class field method尝试找到

  1. private List<ReferenceAnnotationBeanPostProcessor.ReferenceFieldElement> findFieldReferenceMetadata(Class<?> beanClass) {
  2. final List<ReferenceAnnotationBeanPostProcessor.ReferenceFieldElement> elements = new LinkedList();
  3. ReflectionUtils.doWithFields(beanClass, new FieldCallback() {
  4. public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
  5. Reference reference = (Reference)AnnotationUtils.getAnnotation(field, Reference.class);
  6. if (reference != null) {
  7. if (Modifier.isStatic(field.getModifiers())) {
  8. if (ReferenceAnnotationBeanPostProcessor.this.logger.isWarnEnabled()) {
  9. ReferenceAnnotationBeanPostProcessor.this.logger.warn("@Reference annotation is not supported on static fields: " + field);
  10. }
  11. return;
  12. }
  13. elements.add(ReferenceAnnotationBeanPostProcessor.this.new ReferenceFieldElement(field, reference));
  14. }
  15. }
  16. });
  17. return elements;
  18. }

有这个定义的filed或者method 如果存在的话 就建立类定义中对应field method的缓存。同时加入到beanclass/beanname对应该meta信息的缓存 以便同样的请求过来不在解析。

之后 处理调用该函数

  1. public void checkConfigMembers(RootBeanDefinition beanDefinition) {
  2. Set<InjectionMetadata.InjectedElement> checkedElements = new LinkedHashSet(this.injectedElements.size());
  3. Iterator var3 = this.injectedElements.iterator();
  4. while(var3.hasNext()) {
  5. InjectionMetadata.InjectedElement element = (InjectionMetadata.InjectedElement)var3.next();
  6. Member member = element.getMember();
  7. if (!beanDefinition.isExternallyManagedConfigMember(member)) {
  8. beanDefinition.registerExternallyManagedConfigMember(member);
  9. checkedElements.add(element);
  10. if (logger.isDebugEnabled()) {
  11. logger.debug("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
  12. }
  13. }
  14. }
  15. this.checkedElements = checkedElements;
  16. }

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

最后一步 postProcessPropertyValues 注入属性

 

  1. public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
  2. InjectionMetadata metadata = this.findReferenceMetadata(beanName, bean.getClass(), pvs);
  3. try {
  4. metadata.inject(bean, beanName, pvs);
  5. return pvs;
  6. } catch (BeanCreationException var7) {
  7. throw var7;
  8. } catch (Throwable var8) {
  9. throw new BeanCreationException(beanName, "Injection of @Reference dependencies failed", var8);
  10. }
  11. }
  12. public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
  13. Collection<InjectionMetadata.InjectedElement> checkedElements = this.checkedElements;
  14. Collection<InjectionMetadata.InjectedElement> elementsToIterate = checkedElements != null ? checkedElements : this.injectedElements;
  15. if (!((Collection)elementsToIterate).isEmpty()) {
  16. boolean debug = logger.isDebugEnabled();
  17. InjectionMetadata.InjectedElement element;
  18. for(Iterator var7 = ((Collection)elementsToIterate).iterator(); var7.hasNext(); element.inject(target, beanName, pvs)) {
  19. element = (InjectionMetadata.InjectedElement)var7.next();
  20. if (debug) {
  21. logger.debug("Processing injected element of bean '" + beanName + "': " + element);
  22. }
  23. }
  24. }
  25. }

具体过程为判断当前bean 是否需要当前的processor注入 如果需要的话 即执行注入

  1. protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs) throws Throwable {
  2. if (this.isField) {
  3. Field field = (Field)this.member;
  4. ReflectionUtils.makeAccessible(field);
  5. field.set(target, this.getResourceToInject(target, requestingBeanName));
  6. } else {
  7. if (this.checkPropertySkipping(pvs)) {
  8. return;
  9. }
  10. try {
  11. Method method = (Method)this.member;
  12. ReflectionUtils.makeAccessible(method);
  13. method.invoke(target, this.getResourceToInject(target, requestingBeanName));
  14. } catch (InvocationTargetException var5) {
  15. throw var5.getTargetException();
  16. }
  17. }
  18. }

其中 本实例中实际处理inject动作的为

  1. private class ReferenceFieldElement extends InjectedElement
  2. protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
  3. Class<?> referenceClass = this.field.getType();
  4. this.referenceBean = ReferenceAnnotationBeanPostProcessor.this.buildReferenceBean(this.reference, referenceClass);
  5. ReflectionUtils.makeAccessible(this.field);
  6. this.field.set(bean, this.referenceBean.getObject());
  7. }

其中具体的创建代码为

  1. private ReferenceBean<?> buildReferenceBean(Reference reference, Class<?> referenceClass) throws Exception {
  2. String referenceBeanCacheKey = this.generateReferenceBeanCacheKey(reference, referenceClass);
  3. ReferenceBean<?> referenceBean = (ReferenceBean)this.referenceBeansCache.get(referenceBeanCacheKey);
  4. if (referenceBean == null) {
  5. ReferenceBeanBuilder beanBuilder = (ReferenceBeanBuilder)ReferenceBeanBuilder.create(reference, this.classLoader, this.applicationContext).interfaceClass(referenceClass);
  6. referenceBean = (ReferenceBean)beanBuilder.build();
  7. this.referenceBeansCache.putIfAbsent(referenceBeanCacheKey, referenceBean);
  8. }
  9. return referenceBean;
  10. }

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

public class ReferenceBean<T> extends ReferenceConfig<T> 
ReferenceConfig的参数。

此时执行最后一步

this.field.set(bean, this.referenceBean.getObject());

此时尝试去当前referenceBean去除绑定的 dubbo调用invoke对象 如果不存在则创建一个 

具体创建过程比较长 

  1. private void init() {
  2. // 构建参数map
  3. this.ref = this.createProxy(map);
  4. }

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

完。

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/165812
推荐阅读
相关标签
  

闽ICP备14008679号