Spring overriding primary bean with non-primary bean

ε祈祈猫儿з 提交于 2019-12-04 22:52:09

@Primary takes effect only at injection point, when there is a conflict because different beans match the condition to be injected, and a decision needs to be made.

@Primary is not used at beans initialisation. As you are using two different methods creating the same bean, and you are not naming any of them Spring considers you are trying to override it, so this behaviour can happen. Given a name is the easiest solution, but bear in mind that your context will still be initialising the bean you do not want use.

I think you might be missing @ContextConfiguration in your test class.

Example of test configuration class (src/test/java/TestConfiguration.class):

@Configuration
@ComponentScan
public class TestConfiguration {
    @Bean
    RabbitSender rabbitSender() {
        return mock(RabbitSender.class);
    }

}

Example of test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfiguration.class)
public class SomeServiceTest {

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!