2014-07-16 112 views
2

比方說,我用Spring爲我的Java項目,我有以下的接口和類:春輪廓注射:不注射類沒有個人資料

public interface MyInterface { ... } 

@Component 
public class MyInterfaceMainImpl implements MyInterface { ... } 

@Component 
@Profile("mock") 
public class MyInterfaceMockImpl implements MyInterface { ... } 

@ContextConfiguration(locations = {"classpath:my-context.xml"}) 
@ActiveProfiles(profiles = {"mock"}) 
public class MyInterfaceTest extends AbstractTestNGSpringContextTests { 
    @Inject 
    private MyInterface myInterface; 
    ... 
} 

假設我的上下文。 xml在包含我的接口及其實現類的包上啓用組件掃描。當我將配置文件指定爲「模擬」時,出現如下錯誤:「期望單個匹配的bean,但找到2:...」。

任何想法如何我可以避免讓我的非配置文件方法在注入期間成爲一個匹配的bean?或者唯一可能的解決方案是給這個主實現類配置一個配置文件?這是我試圖避免的解決方案。

回答

3

有兩個選項:

  • 使用@Primary以指示當兩個實施方式是本MyInterfaceMockImpl優選:

    @Component 
    @Primary 
    @Profile("mock") 
    public class MyInterfaceMockImpl implements MyInterface { ... } 
    
  • 使用@Profile與否定排除主要執行時mock是活性:

    @Component 
    @Profile("!mock") 
    public class MyInterfaceMainImpl implements MyInterface { ... } 
    
1

另一種選擇是使用@Profile註釋兩個實現,併爲每個實現提供不同的名稱。

@Component 
@Profile("mock") 
public class MyInterfaceMockImpl implements MyInterface { ... } 

@Component 
@Profile("default") 
public class MyInterfaceMainImpl implements MyInterface { ... } 

這種方法的優點是,它允許你指定default作爲在@ActiveProfiles註釋您的測試類的配置文件之一。當然,在這個人爲的例子中不是非常有用,但如果你有三個或更多的配置文件,你可以在不同的測試中使用它,它可以很好地擴展。

2

您還可以使用@Qualifier來指定一個

@Component("main") 
public class MyInterfaceMainImpl implements MyInterface { ... } 

@Component("mock") 
public class MyInterfaceMockImpl implements MyInterface { ... } 



@Inject 
@Qualifer("mock") 
private MyInterface myInterface;