2014-09-04 52 views
1

有沒有辦法在Spring中覆蓋由測試超類設置的@ActiveProfile在Spring框架中覆蓋或覆蓋ActiveProfiles

這裏是我的配置:

<beans profile="integration"> 
    <bean class="org.easymock.EasyMock" factory-method="createMock"> 
     <constructor-arg value="com.mycompany.MyInterface" /> 
    </bean> 
</beans> 

<beans profile="production,one-off-test"> 
    <bean class="com.mycompany.MyInterfaceImpl" /> 
</beans> 

超類中的所有測試看起來是這樣的:

@ActiveProfiles("integration") 
public abstract class TestBase { 

而且在我的新測試類,我想這樣做:

@ActiveProfiles("one-off-test") 
public class MyTest extends TestBase { 

不從TestBase繼承不是一個真正的選擇。 當我嘗試運行它,我得到的錯誤是:

No qualifying bean of type [com.mycompany.MyInterface] is defined: expected single matching bean but found 2 
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.mycompany.MyInterface] is defined: expected single matching bean but found 2: org.easymock.EasyMock#1,com.mycompany.MyInterfaceImpl#0 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:970) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) 
    ... 46 more 

什麼是更好的是要能夠層剖面,所以如果一個bean存在輪廓one-off-test注射的是那個,否則注入integration配置文件bean。

任何幫助將不勝感激。

回答

0

一個解決方案是你提出的問題是使用primary這樣的:

<beans profile="integration"> 
    <bean class="org.easymock.EasyMock" factory-method="createMock" primary=true> 
     <constructor-arg value="com.mycompany.MyInterface" /> 
    </bean> 
</beans> 

你不需要改變任何東西,因爲春天將從輪廓integration使用bean地方MyInterface類型的豆。儘管事實上存在多個這種類型的bean,Spring仍然這樣做。

檢查出this它給出了一些關於primary如何工作的更多細節。

+0

美麗和優雅的解決方案。謝謝! – 2014-09-06 00:00:34

+0

我很高興你喜歡它: - )!!! – geoand 2014-09-06 06:26:07

5

您可能需要通過系統屬性來指定活動概況:萬一

-Dspring.profiles.active="integration" 

要使用相關bean實現或

-Dspring.profiles.active="one-off-test" 

使用一次性測試個人資料豆。

然後,你將需要設置inheritProfiles註釋propertyto false這將阻止當前註釋測試用例discart子型材:

@ActiveProfiles(profiles = {"one-off-test"}, inheritProfiles= false) 
public class MyTest extends TestBase {} 
+0

不錯! +1! 'inheritProfiles'的存在讓我的心情滑了下來 – geoand 2014-09-05 15:10:08

+1

是的,如果遇到類似的情況,我甚至可能會遇到下滑:D – tmarwen 2014-09-05 15:13:21