Dubbo 源码阅读(四)injectExtension

本文深入探讨了Dubbo框架中SPI(Service Provider Interface)机制的工作原理,详细解释了如何通过set方法注入@SPI接口实例,以及ExtensionLoader和AdaptiveExtensionFactory在实现动态代理和扩展加载过程中的作用。
部署运行你感兴趣的模型镜像

一个实现类里需要依赖另一个 @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;
}

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值