Skip to content
Advertisement

spring boot boostrap bean override

In my spring.factories I have such a definition:

org.springframework.cloud.bootstrap.BootstrapConfiguration=
     MyBootstrapConfiguration

In MyBootstrapConfiguration I have :

@Configuration
public class MyBootstrapConfiguration {
    
     @Bean
     @ConditionalOnMissingBean
     public ApiClient apiClient() {
         return someClient;
     }
}

Now in my test (junit-5 and @SpringBootTest), I would like to override this bean. Notice the @ConditionalOnMissingBean… If I can hook somehow to a “before” my bootstrap is started, to provide that ApiClient, that method apiClient would obviously not be called and I would be happy.

Please notice that MyBootstrapConfiguration is not something I have control of – its an invariant to me. For non-bootstrap configuration this is easily doable, but is there a way to do this for bootstrap?

Advertisement

Answer

Given a test configuration class:

@Configuration
public class TestBootstrapConfiguration implements Ordered {
    
    @Bean
    public ApiClient testApiClient() {
        return testApiClient;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}

In src/test/resources/META-INF/spring.factories

org.springframework.cloud.bootstrap.BootstrapConfiguration=
TestBootstrapConfiguration
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement