关于Spring bean 注入时有多个候选bean的解决方案

百般思念 提交于 2019-12-02 08:39:53

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;
   }



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!