在Spring Framework中分层或覆盖ActiveProfile

Eug*_*nko 2 java spring integration-testing

有没有办法@ActiveProfile在Spring中覆盖测试超类的集合?

这是我的配置:

<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>
Run Code Online (Sandbox Code Playgroud)

所有测试的超类看起来像这样:

@ActiveProfiles("integration")
public abstract class TestBase {
Run Code Online (Sandbox Code Playgroud)

在我的新测试课中,我想这样做:

@ActiveProfiles("one-off-test")
public class MyTest extends TestBase {
Run Code Online (Sandbox Code Playgroud)

不继承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
Run Code Online (Sandbox Code Playgroud)

更好的是能够对配置文件进行分层,以便在存在用于配置文件one-off-test注入的bean时,否则注入integration配置文件bean.

任何帮助将受到高度赞赏.

tma*_*wen 6

您可能需要通过"系统属性"指定活动的配置文件:

-Dspring.profiles.active="integration"
Run Code Online (Sandbox Code Playgroud)

如果你想使用相关的bean实现或

-Dspring.profiles.active="one-off-test"
Run Code Online (Sandbox Code Playgroud)

使用一次性测试配置文件bean.

然后,您必须设置inheritProfiles注释属性false,以防止当前带注释的测试用例丢弃子类配置文件:

@ActiveProfiles(profiles = {"one-off-test"}, inheritProfiles= false)
public class MyTest extends TestBase {}
Run Code Online (Sandbox Code Playgroud)


geo*_*and 0

您提出的问题的一种解决方案是primary像这样使用:

<beans profile="integration">
    <bean class="org.easymock.EasyMock" factory-method="createMock" primary=true>
        <constructor-arg value="com.mycompany.MyInterface" />
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

您不需要更改任何其他内容,因为 Spring 将integration在任何类型为 的 bean处使用配置文件中的 bean MyInterface。尽管存在多个该类型的 bean,Spring 仍然这样做。

查看此内容,其中提供了有关工作原理的更多详细信息primary