Dubbo 源码阅读(四)injectExtension

一个实现类里需要依赖另一个 @SPI 接口的实例,怎么办?

如下示例,你需要写一个 set 方法:

public class OrderServiceImpl implements OrderService {
    private InfoService infoService;//是dubbo的扩展点,是spring的bean接口

    public void setInfoService(InfoService infoService) {
        this.infoService = infoService;
    }
}

Dubbo 源码阅读(一)getExtensionLoader 和 getExtension 里,看 createExtension 方法,可以看到,里面有一步是 injectExtension(instance);为什么要写一个 setXX 方法,原因就在这里面:

 private T injectExtension(T instance) {
    try {
        if (objectFactory != null) {
            for (Method method : instance.getClass().getMethods()) {
            	//如果有一个方法以set开头,入参长度为1
                if (method.getName().startsWith("set")
                        && method.getParameterTypes().length == 1
                        && Modifier.isPublic(method.getModifiers())) {
                    /**
                     * Check {@link DisableInject} to see if we need auto injection for this property
                     */
                    if (method.getAnnotation(DisableInject.class) != null) {
                        continue;
                    }
                    Class<?> pt = method.getParameterTypes()[0];
                    try {
                    	//拿到入参方法set后面的字符串,首字母小写
                        String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
                        //先拿property的Extension
                        Object object = objectFactory.getExtension(pt, property);
                        if (object != null) {
                            method.invoke(instance, object);
                        }
                    } catch (Exception e) {
                        logger.error("fail to inject via method " + method.getName()
                                + " of interface " + type.getName() + ": " + e.getMessage(), e);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return instance;
}

跟 getExtension:

@SPI
public interface ExtensionFactory {

    /**
     * Get extension.
     *
     * @param type object type.
     * @param name object name.
     * @return object instance.
     */
    <T> T getExtension(Class<T> type, String name);

}

它有3个实现:
在这里插入图片描述
其中,AdaptiveExtensionFactory 是打了 @Adaptive 注解的,说明它是被优先实现的,但是在。

@Adaptive
public class AdaptiveExtensionFactory implements ExtensionFactory {

    private final List<ExtensionFactory> factories;

    public AdaptiveExtensionFactory() {
    	//拿到所有的ExtensionFactory实例
        ExtensionLoader<ExtensionFactory> loader = ExtensionLoader.getExtensionLoader(ExtensionFactory.class);
        List<ExtensionFactory> list = new ArrayList<ExtensionFactory>();
        for (String name : loader.getSupportedExtensions()) {
            list.add(loader.getExtension(name));
        }
        factories = Collections.unmodifiableList(list);
    }

    @Override
    public <T> T getExtension(Class<T> type, String name) {
    	//SpiExtensionFactory SpringExtensionFactory
        for (ExtensionFactory factory : factories) {
            T extension = factory.getExtension(type, name);
            if (extension != null) {
            	//如果能通过SpiExtensionFactory得到直接返回
                return extension;
            }
        }
        return null;
    }

}

AdaptiveExtensionFactory 在哪里创建的呢? 在创建 ExtensionLoader 的时候

private ExtensionLoader(Class<?> type) {
    this.type = type;
    objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}

回到上一段代码,跟 getSupportedExtensions:

public Set<String> getSupportedExtensions() {
	  //别名
   Map<String, Class<?>> clazzes = getExtensionClasses();
   											//按别名排序
   return Collections.unmodifiableSet(new TreeSet<String>(clazzes.keySet()));
   //SpiExtensionFactory     在前面
   //SpringExtensionFactory  在后面
}

再看看 SpiExtensionFactory 和 SpringExtensionFactory 的 getExtension:
类 SpiExtensionFactory

public class SpiExtensionFactory implements ExtensionFactory {

    @Override
    public <T> T getExtension(Class<T> type, String name) {
        if (type.isInterface() && type.isAnnotationPresent(SPI.class)) {
            ExtensionLoader<T> loader = ExtensionLoader.getExtensionLoader(type);
            if (!loader.getSupportedExtensions().isEmpty()) {
                return loader.getAdaptiveExtension();
            }
        }
        return null;
    }
}

类 SpringExtensionFactory

@Override
@SuppressWarnings("unchecked")
public <T> T getExtension(Class<T> type, String name) {
    for (ApplicationContext context : contexts) {
        if (context.containsBean(name)) {
            Object bean = context.getBean(name);
            if (type.isInstance(bean)) {
                return (T) bean;
            }
        }
    }

    logger.warn("No spring extension (bean) named:" + name + ", try to find an extension (bean) of type " + type.getName());

    if (Object.class == type) {
        return null;
    }

    for (ApplicationContext context : contexts) {
        try {
            return context.getBean(type);
        } catch (NoUniqueBeanDefinitionException multiBeanExe) {
            logger.warn("Find more than 1 spring extensions (beans) of type " + type.getName() + ", will stop auto injection. Please make sure you have specified the concrete parameter type and there's only one extension of that type.");
        } catch (NoSuchBeanDefinitionException noBeanExe) {
            if (logger.isDebugEnabled()) {
                logger.debug("Error when get spring extension(bean) for type:" + type.getName(), noBeanExe);
            }
        }
    }

    logger.warn("No spring extension (bean) named:" + name + ", type:" + type.getName() + " found, stop get bean.");

    return null;
}
发布了185 篇原创文章 · 获赞 271 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44367006/article/details/105239055