title: Spring overriding primary bean with non-primary bean
body: <p>I am trying to override a Spring bean during a test declared in a test configuration with the use of @Primary.  One declaration is in the src/main/java path, the other, the primary, is in src/test/java path.</p>
  <p>However, Spring is intentionally replacing the primary bean with the the non-primary bean, the one I don't want to use for the test.  If I simply comment out the production (src/main/java) configuration bean, it uses the primary test (src/main/test) bean in the test configuration as desired.  (Clearly I can't comment out code every time I want to run a test.)</p>
  <p>From the logs:</p>
  <blockquote>
  <p>o.s.b.f.s.DefaultListableBeanFactory - <strong>Overriding bean definition for bean 'sqsConnectionFactory' with a different definition: replacing</strong> [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; <strong>primary=true;</strong> factoryBeanName=testJmsConfiguration; factoryMethodName=sqsConnectionFactory; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/foo/configuration/TestJmsConfiguration.class]]</p>
  <p>with</p>
  <p>[Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; <strong>primary=false</strong>; factoryBeanName=jmsConfiguration; factoryMethodName=sqsConnectionFactory; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/foo/configuration/JmsConfiguration.class]]</p>
  </blockquote>
  <p><strong>Why is spring replacing a primary bean with a non-primary bean and how do I get Spring to use the bean specifically marked as the primary bean?</strong></p>
  <p>Edit:
  The src/main/java configuration:</p>
  <pre><code>@Configuration
  public class JmsConfiguration {
  
  ... other bean declarations here ...
  
  @Bean
  public SQSConnectionFactory sqsConnectionFactory(Region region) throws JMSException {
      return SQSConnectionFactory.builder()
              .withRegion(region)
              .build();
  }
  }
  </code></pre>
  <p>The test configuration:</p>
  <pre><code>@Configuration
  public class TestJmsConfiguration {
  
  @Bean(name=&quot;messageProducerMock&quot;)
  public MessageProducer mockMessageProducer() {
      return new MessageProducerMock();
  }
  
  ... other bean declarations here ...
  
  @Bean
  @Primary
  public SQSConnectionFactory sqsConnectionFactory(@Qualifier(&quot;messageProducerMock&quot;) MessageProducer messageProducerMock) throws JMSException {
      ... returning setup mock here
  }
  }
  </code></pre>
  <p>The class with the tests is annotated with:</p>
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest
  @ActiveProfiles(profiles = {&quot;test&quot;})
  </code></pre>