org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.jms.ConnectionFactory' available: expected single matching bean but found 2: activeMQConnectionFactory,springFactory
今天使用springboot Demo ActiveMQ過程當中,注入ConnectionFactory
時,SpringBoot 自動配置時發現由於多個候選bean注入失敗,解決此問題有兩個方法:java
// 1. 當bean定義階段和bean注入階段代碼均可以修改時優先採用@Qualifier註解在bean注入階段解決,使用以前須要先得到bean的名稱; @Autowired @Qualifier(value = "activeMQConnectionFactory") public ActiveMQConnectionFactory mqConnectionFactory; @Bean(name = "activeMQConnectionFactory") public ActiveMQConnectionFactory activeMQConnectionFactory(){ ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(); activeMQConnectionFactory.setBrokerURL(BROKERURL); activeMQConnectionFactory.setUserName(USERNAME); activeMQConnectionFactory.setPassword(PASSWORD); activeMQConnectionFactory.setTrustAllPackages(true); return activeMQConnectionFactory; } @Bean(name = "springFactory") // @Primary public CachingConnectionFactory connectionFactory(){ CachingConnectionFactory factory = new CachingConnectionFactory(mqConnectionFactory); factory.setSessionCacheSize(100); factory.setCacheConsumers(true); factory.setCacheProducers(true); return factory; } // 2. 但遇到像springboot自動配置這種狀況,沒法改動@AutoWired階段的代碼,因此只能採起在@Bean階段加上註解配置@primary @Bean(name = "springFactory") @Primary // 默認優先調用該bean public CachingConnectionFactory connectionFactory(){ CachingConnectionFactory factory = new CachingConnectionFactory(mqConnectionFactory); factory.setSessionCacheSize(100); factory.setCacheConsumers(true); factory.setCacheProducers(true); return factory; }