问题描述
使用禁用Spring Boot 2.1 bean覆盖默认情况下,这是一件好事.
With Spring Boot 2.1 bean overriding is disabled by default, which is a good thing.
但是,我确实进行了一些测试,在这些测试中,我使用Mockito用模拟的实例替换了bean.使用默认设置时,具有此类配置的测试将因Bean覆盖而失败.
However I do have some tests where I replace beans with mocked instances using Mockito. With the default setting Tests with such a configuration will fail due to bean overriding.
我发现可行的唯一方法是通过应用程序属性启用bean覆盖:
The only way I found worked, was to enable bean overriding through application properties:
spring.main.allow-bean-definition-overriding=true
但是,我真的很想确保为我的测试配置设置最少的bean定义,这将在禁用覆盖的Spring指出.
However I would really like to ensure minimal bean definition setup for my test configuration, which would be pointed out by spring with the overriding disabled.
我要覆盖的bean要么是
The beans that I am overriding are either
- 在导入我的测试配置的另一个配置中定义
- 通过注释扫描自动发现的豆子
我认为应该在覆盖Bean的测试配置中起作用,并在其上拍上 @Primary
,因为我们习惯于数据源配置.但是,这没有效果,让我感到奇怪: @Primary
和禁用的Bean覆盖是否矛盾?
What I was thinking should work in the test configuration overriding the bean and slap a @Primary
on it, as we are used to for data source configurations. This however has no effect and got me wondering: Is the @Primary
and the disabled bean overriding contradictory?
一些例子:
package com.stackoverflow.foo;
@Service
public class AService {
}
package com.stackoverflow.foo;
public class BService {
}
package com.stackoverflow.foo;
@Configuration
public BaseConfiguration {
@Bean
@Lazy
public BService bService() {
return new BService();
}
}
package com.stackoverflow.bar;
@Configuration
@Import({BaseConfiguration.class})
public class TestConfiguration {
@Bean
public BService bService() {
return Mockito.mock(BService.class);
}
}
推荐答案
覆盖Bean意味着在上下文中可能只有一个具有唯一名称或ID的Bean.因此,您可以通过以下方式提供两个bean:
Overriding beans means that there may be only one bean with a unique name or id in the context. So you can provide two beans in the following way:
package com.stackoverflow.foo;
@Configuration
public class BaseConfiguration {
@Bean
@Lazy
public BService bService1() {
return new BService();
}
}
package com.stackoverflow.bar;
@Configuration
@Import({BaseConfiguration.class})
public class TestConfiguration {
@Bean
public BService bService2() {
return Mockito.mock(BService.class);
}
}
如果添加 @Primary
,则默认情况下将在以下位置注入主bean:
If you add @Primary
then primary bean will be injected by default in:
@Autowired
BService bService;
这篇关于Spring Boot 2.1 Bean Override vs.Primary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!