spring ioc注入接口的具体实现来测试

2024-01-14

我有以下设置:

@Component
public class ImplOne implements IFace{
}

@Component
public class ImplTwo implements IFace{
}

public interface IFace{
}

我正在尝试按类型获取 ImplOne 的引用:

@RunWith(SpringJUnit4ClassRunner.class)
public class ImplOneTest {
  @Autowired
  private ImplOne impl;

  @Test
  public void test(){
    Assert.assertNotNull(impl);
  }
}

尽管如此,我得到以下例外:

org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [some.package.TestBean] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

我尝试了以下解决方法:

  • 从 ImplOne 中删除“implements IFace”,以便实现类本身由 cglib 代理。不可接受,因为我还需要能够在我的应用程序代码中获取 IFace 的所有实现。
  • 通过a进行方法注入@Autowired public void setImplOne(IFace[] beans)并且通过instanceof检查过滤实例不起作用,因为注入的bean是java.lang.reflect.Proxy类型的子类,它不提供任何有用的方法。
  • 将 ImplOne 的 @Component 更改为 @Component("implone") 并使用 @Qualifier("implone")。

Code:

@RunWith(SpringJUnit4ClassRunner.class)
public class ImplOneTest {
  @Autowired
  @Qualifier("implone")
  private ImplOne impl;

  @Test
  public void test(){
    Assert.assertNotNull(impl);
  }
}

但我不喜欢必须命名我的 bean 才能注入具体实现的想法。

有没有办法优雅地做到这一点,或者至少以某种只影响我的测试代码的方式?还有一些特殊原因导致我的第一个示例不受支持吗?


  1. 检查异常是否与您认为的 Bean 有关。因为名字不匹配
  2. 即使 1 是固定的,最好通过接口自动装配,而不是通过具体实现。大多数情况下(我不知道您的情况是否属实),具体实现由 spring 代理(例如,用于事务支持),并且只能通过接口注入。由于一个接口有两个实现,因此您必须提供一个名称,或者使用@Autowired + @Qualifier,或使用@Resource(name="")注入你想要的东西。这并没有什么问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

spring ioc注入接口的具体实现来测试 的相关文章

随机推荐