2016-04-29 27 views
0

基本上我有两个bean实现相同的接口。一个是配置文件“默认”,另一个是“整合”。创建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) {...} 

到目前为止好,我也看到了存根豆被称为在集成测试。然后,我想在我的集成测试注入一些测试数据存根豆:

@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不是接口,仍然会得到相同的消息。

+0

代码,我不能重现此。请提供[MCVE]。 –

+0

对不起,我是Spring的新手,这是我们生产代码的一部分。我不知道如何提取出来。 –

回答

0

您应与Autowired一个旁边加上注释Qualifier指定哪些bean必须被实例化:

@Autowired 
@Qualifier("my-bean") 
+0

他们已经通过'@ Profile'实现了这一点。在集成测试期间,以上只有一个豆类将处于活动状态。无论如何,这并不能解释为什么Spring试图实例化一个接口。 –

0

原因它试图注入SomeClientIfc是因为你叫变量“someClientIfc”。

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

一种方式是如上面一点桑蒂提到,另一种方式是命名变量“stubSomeNIOClient”见下文

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

问题不在注射上。当前失败OP询问的是'无法实例化[com.audiencescience.some.client.SomeClientIfc]'。你的回答并不能解释为什么Spring试图实例化这种类型。 –

相关问题