Error Message
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注入失败,解决此问题有两个方法:
// 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;
}
来源:oschina
链接:https://my.oschina.net/u/2704118/blog/1865818