I am trying to override the Spring bean during a test declared in a test configuration using @Primary. One declaration is in the src / main / java path, another, primary, is in the src / test / java path.
However, Spring intentionally replaces the primary bean with a non-primary bean, which I do not want to use for the test. If I just comment out the production configuration of the (src / main / java) bean, it uses the primary test (src / main / test) bean in the test configuration as desired. (Clearly, I cannot comment on the code every time I want to run a test.)
From the magazines:
osbfsDefaultListableBeanFactory - Override the bean definition for the bean 'sqsConnectionFactory' with another definition: replace [Root bean: class [null]; Volume =; abstract = false; lazyInit = false; autowireMode = 3; dependencyCheck = 0; autowireCandidate = TRUE; primary = true; factoryBeanName = testJmsConfiguration; factoryMethodName = sqsConnectionFactory; initMethodName = NULL; destroyMethodName = (output); defined in the class path resource [com / foo / configuration / TestJmsConfiguration.class]]
from
[Root bean: class [null]; Volume =; abstract = false; lazyInit = false; autowireMode = 3; dependencyCheck = 0; autowireCandidate = TRUE; primary = false ; factoryBeanName = jmsConfiguration; factoryMethodName = sqsConnectionFactory; initMethodName = NULL; destroyMethodName = (output); defined in the class path resource [com / foo / configuration / JmsConfiguration.class]]
Why is Spring replacing the primary bean with a non-primary bean, and how can I get Spring to use a bean specifically labeled as a primary bean?
Edit: src / main / java configuration:
@Configuration public class JmsConfiguration { ... other bean declarations here ... @Bean public SQSConnectionFactory sqsConnectionFactory(Region region) throws JMSException { return SQSConnectionFactory.builder() .withRegion(region) .build(); } }
Test Configuration:
@Configuration public class TestJmsConfiguration { @Bean(name="messageProducerMock") public MessageProducer mockMessageProducer() { return new MessageProducerMock(); } ... other bean declarations here ... @Bean @Primary public SQSConnectionFactory sqsConnectionFactory(@Qualifier("messageProducerMock") MessageProducer messageProducerMock) throws JMSException { ... returning setup mock here } }
A class with tests is annotated with:
@RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles(profiles = {"test"})
java spring spring-boot spring-test dependency-injection
FiguringThisOut
source share