apache / dubbo-spring-boot-project

Spring Boot Project for Apache Dubbo
https://dubbo.apache.org
Apache License 2.0
5.41k stars 1.88k forks source link

能否通过springcontext 获取到bubbo的bean #817

Closed star362 closed 1 year ago

star362 commented 1 year ago

一个接口有两个实现类,使用不同的group 。在调用接口的时候需要根据不同的业务场景获取不同的实现类。类似于策略模式。所以我想通过getbean 的方式实现。请问可以吗?

AlbumenJ commented 1 year ago

通过 context 获取需要去判断 dubbo 生成名字的逻辑,建议直接通过注解注入使用

star362 commented 1 year ago

通过注解也是可以实现的。不过我觉得代码写的不够优雅。需要写很多的 if else,我就是想知道是否能用代码实现。

star362 commented 1 year ago

有没有什么代码参考。或者思路也行。

star362 commented 1 year ago

@Component public class TrilateralContext {

@DubboReference(group = "Service", version = "1.0", check = false)
TrilateralHandle trilateralHandle;

public TrilateralHandle getTrilateralBean(String group) {
    Assert.notNull(group,  "group not null !!");
    return SpringUtil.getBean(ReferenceAnnotationBeanPostProcessor.class)
            .getReferenceBeans().stream()
            .filter(a -> a.getGroup().equals(group) && a.getObjectType() == TrilateralHandle.class)
            .map(a -> (TrilateralHandle) a.getObject()).findFirst().orElseThrow(() -> new IllegalArgumentException( "获取 buddo 服务异常!!!"));

}

}

我用ReferenceAnnotationBeanPostProcessor 也可以实现,不过就是需要在类中添加 @DubboReference 否则就获取不到。