具有多个接口实现的Spring Autowire注释

奥马尔·阿尔·卡巴吉(Omar Al Kababji):

假设您有一个界面

public interface A {
  public void doSomething();
}

和两个实现类

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

}

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

}

最后是一个使用“ A”实现的类:

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

现在,如果要注入AImpl1,请添加@Qualifier(“ aImpl1”),如果要注入AImpl2,请添加@Qualifier(“ aImpl2”)

问题是:是否可以指示spring在这种情况下以AImpl1AImpl2查找“ A”的所有实现,并使用一些特定于应用程序的约定来选择最合适的实现?例如,在这种情况下,我的约定可以使用具有最大后缀的实现(即AImpl2)?

编辑:类MyClass完全不应该知道实现查找逻辑,它应该只找到其属性“ a”,并使用AImpl2对象设置。

garst:

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

您可以创建一个自定义BeanDefinitionRegistryPostProcessor并实现方法postProcessBeanDefinitionRegistrypostProcessBeanFactory

这样,您可以在实例化和注入之前访问所有 bean定义。逻辑确定每个接口的首选实现,然后将其设置为primary

@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)

    }



}

困难的部分是查找bean名称,这取决于您应用程序的具体情况。我想拥有一致的命名约定会有所帮助。

更新:

界面中的两种方法似乎都BeanDefinitionRegistryPostProcessor可以用于此目的。请记住,在此postProcessBeanDefinitionRegistry阶段,通过@configuration类配置的bean尚不可用,如下面的注释中所述。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章