2014-09-04 142 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