When running tests in my Spring Boot application, I am encountering unexpected behavior with bean overriding. Despite having spring.main.allow-bean-definition-overriding=true in the test properties, the bean defined in TestConfig does not take precedence over the one in Config, even though it is annotated with @Primary.

Steps to Reproduce:

Application Configuration (Config.java):

@Configuration
public class Config {
    @Bean
    public String test() {
        System.out.println("Config");
        return "normal";
    }
}

Test Configuration (TestConfig.java):

@TestConfiguration
public class TestConfig {
    @Primary
    @Bean
    public String test() {
        System.out.println("TestConfig");
        return "test";
    }
}

Test Setup:

@SpringBootTest
@Import(TestConfig.class)
class DemoApplicationTests {

    @Test
    void contextLoads() {
        // Test code here
    }
}

Expected Behavior: The bean from TestConfig should override the one in Config, as @Primary is specified, and spring.main.allow-bean-definition-overriding=true is set. The test should print "TestConfig" indicating that the TestConfig bean is being used.

Actual Behavior: The bean from Config is being used instead, and the output is "Config".

Workaround Attempted: Ensuring that spring.main.allow-bean-definition-overriding=true is set, and using @Primary on the bean in TestConfig, but the issue persists.

Additional Notes: This behavior may indicate an issue with how Spring Boot is handling bean overriding in test contexts when both @Configuration and @TestConfiguration are involved.

Request: Please advise on whether this is a bug or if there is an alternative approach to ensure the correct bean overriding behavior during testing.

Comment From: wilkinsona

Can you please provide a minimal sample that reproduces the problem? Right now, we don't even know which version of Spring Boot you're using.

Comment From: oleksiizaitsev7

Can you please provide a minimal sample that reproduces the problem? Right now, we don't even know which version of Spring Boot you're using.

Spring Boot: 3.3.5 Sure demo.zip

Comment From: wilkinsona

Thanks for the sample. It's an ordering problem. With the arrangement in your sample, TestConfig is processed first and defines its test bean with the value test. Config is processed second and it overrides the test bean with its value of normal.

One way to change the ordering such that it works as you would like is to nest TestConfig within DemoApplicationTests.

If you have any further questions, please follow up on Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.