创建bean是错误的,因为它是一个接口?

时间:2016-04-29 18:35:37

标签: java spring javabeans

基本上我有两个bean实现相同的接口。一个用于个人资料"默认"和另一个"整合"。

public interface SomeClientIfc { ... }

@Component
@Profile(value={"functional", "integration"})
public class StubSomeNIOClient implements SomeClientIfc {...}

public class SomeNIOClient implements SomeClientIfc {...}

@Configuration
@Profile("default")
public class SomeClientConfiguration {
  @Bean
  public SomeClientIfc someClient() {
      ...
    SomeNIOClient someClient = new SomeNIOClient(numberOfParititions, controllerHosts, maxBufferReadSize,
        connectionPoolSize);
    return someClient;
  }
}

在产品代码中

   @Autowired
   public SomeUserResolver(..., SomeClientIfc someClient) {...}

到目前为止,我确实看到在集成测试中调用了存根bean。然后我想在集成测试中将一些测试数据注入到存根bean中:

@ContextConfiguration(locations = {"/configProperties.xml", "/integrationTests.xml", ...})
@ActiveProfiles("integration")
public class SomeTestBase {
  @Autowired
  private SomeClientIfc someClientIfc;
}

然而,在运行测试时,我收到了错误消息

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someClientIfc': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.audiencescience.some.client.SomeClientIfc]: Specified class is an interface

我甚至尝试用StubSomeNIOClient替换SomeClientIfc,但仍然得到相同的消息,即使StubSomeNIOClient不是接口。

2 个答案:

答案 0 :(得分:0)

您应该添加Qualifier注释以及Autowired注释,以指定必须实例化哪个bean:

@Autowired
@Qualifier("my-bean")

答案 1 :(得分:0)

它试图注入SomeClientIfc的原因是你调用了变量'someClientIfc'。

在集成环境中,您已初始化了所有3个类:SomeClientIfc,StubSomeNIOClient和SomeNIOClient。这给春天造成了困惑,幸运的是有办法解决这种混乱。

一种方式如上所述,Little Santi,另一种方法是命名变量'stubSomeNIOClient',参见下面的代码

@ContextConfiguration(locations = {"/configProperties.xml", "/integrationTests.xml", ...})
@ActiveProfiles("integration")
public class SomeTestBase {
  @Autowired
  private SomeClientIfc stubSomeNIOClient;
}