当前位置: 首页 > 知识库问答 >
问题:

带有几个接口实现的Spring Autowire注释

吴均
2023-03-14

假设您有一个接口

public interface A {
  public void doSomething();
}

和两个实现类

@Component(value="aImpl1")
public class AImpl1 implements A {

}

@Component(value="aImpl2")
public class AImpl2 implements A{

}
@Component
public class MyClass {
  @Autowire
  A a;
}

共有1个答案

东门航
2023-03-14

假设您已经有数百个接口和实现(正如您在评论中所说),并且您不想重构所有代码······然后是一个棘手的问题...这是一个棘手的解决方案:

您可以创建自定义BeanDefinitionRegistryPostProcessor并实现方法PostProcessBeanDefinitionRegistryPostProcessBeanFactory

通过这种方式,您可以在实例化和注入所有bean定义之前访问它们。执行逻辑,找出每个接口的首选实现,然后将该接口设置为主要实现。

@Component
public class CustomBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(
            BeanDefinitionRegistry registry) throws BeansException {

          // this method can be used to set a primary bean, although 
          // beans defined in a @Configuration class will not be avalable here.

    }

    @Override
    public void postProcessBeanFactory(
            ConfigurableListableBeanFactory beanFactory) throws BeansException {     

        // here, all beans are available including those defined by @configuration, @component, xml, etc.

        // do some magic to somehow find which is the preferred bean name for each interface 
        // you have access to all bean-definition names with: beanFactory.getBeanDefinitionNames()
        String beanName = "aImpl2"; // let's say is this one

        // get the definition for that bean and set it as primary
        beanFactory.getBeanDefinition(beanName).setPrimary(true)

    }



}

另一方面,它们确实可以在PostProcessBeanFactory中使用。

 类似资料:
  • 我有这个问题,无法理解如何修复它,任何帮助都将得到评估。我需要用一些身份验证来保护REST方法,并且我在我的应用程序中有几个角色。我在我的类中的方法中放置了注释,实现了一些接口和Spring没有创建没有任何日志消息的bean(在我的例子中)。但是如果类没有实现接口-bean创建得很好。 在代码中,它如下所示: 控制器: 接口: 在我的情况下,控制器bean没有创建。但是如果我删除一切都会正常工作,

  • 我正在实现一个Java图形库(学习...)。因此,我写了一个界面 作为实现的第一步,我正在编写实现上述接口的Digram类。然而,为了简单起见,我希望节点标识符为整数,因此我将函数定义为 但是,我遇到了错误,我需要用超类型覆盖或实现方法。有人可以向我解释这种行为的基础吗?此外,如果有人可以解释,我们如何设计允许灵活地添加任何类型组件的库。

  • 看来Guice正在尝试使用不同于预期的创建方法。你知道怎么解决这个问题吗?如有任何指示,将不胜感激! 谢谢!

  • 问题内容: 有没有理由不将Controller映射为接口? 在所有的示例和问题中,我看到了周围的控制器,都是具体的类。是否有一个原因?我想将请求映射与实现分开。但是,当我尝试在具体类中获取a 作为参数时,我碰壁了。 我的Controller界面如下所示: And the implementing class: 该方法效果很好;在抛出一个异常 如果我将注释添加到具体类中,那么一切都会按预期工作,但是

  • 问题内容: 考虑以下代码: 由于类型擦除的限制,我收到以下错误消息: java.lang.Comparable的不能使用不同的参数继承:和 我有以下要求: 需要是一个枚举,因为我需要将其用作注释中的默认值。 我的界面的约定是,它必须具有可比性。 我已经尝试在接口中使用通用范围,但是Java不支持此功能。 问题答案: 枚举实现Comparable,因此FooImpl最终使用不兼容的参数将Compar

  • 我是个新手,所以请不要介意我的问题是愚蠢的 我有一个实现两个接口的类 我正在上下文类中定义bean对象,如下所示: