Spring boot 2.1 bean override vs. Primary

后端 未结 4 861
名媛妹妹
名媛妹妹 2020-12-28 14:04

With Spring Boot 2.1 bean overriding is disabled by default, which is a good thing.

However I do have some tests where I replace beans with mocked instances using Mo

4条回答
  •  死守一世寂寞
    2020-12-28 14:20

    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);
        }
    }
    

    If you add @Primary then primary bean will be injected by default in:

    @Autowired
    BService bService;
    

提交回复
热议问题