gpt4 book ai didi

java - 在 Spring 框架中分层或覆盖 ActiveProfiles

转载 作者:行者123 更新时间:2023-12-02 00:37:56 25 4
gpt4 key购买 nike

有没有办法覆盖Spring中测试父类(super class)设置的@ActiveProfile

这是我的配置:

<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>

所有测试的父类(super class)如下所示:

@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 就可以注入(inject)它,否则注入(inject)集成 配置文件 bean。

任何帮助将不胜感激。

最佳答案

您可能需要通过系统属性指定 Activity 配置文件:

-Dspring.profiles.active="integration"

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

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

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

然后,您必须将 inheritProfiles 注释属性设置为 false,这将阻止当前带注释的测试用例放弃子类配置文件:

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

关于java - 在 Spring 框架中分层或覆盖 ActiveProfiles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25675186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com