【问题标题】:While @Autowired with @Qualifier in Junit Test Case showing Unable load application context and Illegalstate exception在 Junit 测试用例中 @Autowired 和 @Qualifier 显示无法加载应用程序上下文和非法状态异常
【发布时间】:2020-06-04 23:34:31
【问题描述】:

我在我的应用程序中使用@KafkaListener,这就是我使用的原因

@Configuration
static class ContextConfiguration { 
          //create the beans
     }

我的班级使用@Autowired @Qualifier("someName") 进行配置,同时编写符合“someName”的测试类配置未加载..

所以它会抛出错误

引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:否 'org.springframework.web.client.RestTemplate' 类型的限定 bean


available:预计至少有 1 个符合自动装配条件的 bean 候选人。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=someName)}

【问题讨论】:

  • 你在使用 mockito,如果是 - 尝试为它注入模拟
  • 我想检查真正的连接,这是我需要配置 bean 的主要测试类

标签: junit kafka-consumer-api illegalstateexception context-configuration


【解决方案1】:

在这种情况下,主要问题是 @Bean("someName") 没有加载到 Spring 容器中,因此在创建 bean 时,破解在 @Bean("someName") 下返回的配置,例如......

@Configuration
    static class ContextConfiguration {
        @Bean
        @Qualifier("InternalKafkaProducer")
        public KafkaTemplate<Object, Object> publishingTemplate(){
            return new KafkaTemplate(new DefaultKafkaProducerFactory<>(getKafkaTemplate()));

        }
    } 
@Autowired
 private KafkaTemplate<Object, Object> kafkaTemplate;
@Test
public void test(){
  //some code
}

private static HashMap<String, Object> getKafkaTemplate() {
        //return the properties;
}
}//test class end

Main class
@Autowired
@Qualifier("someName")
private KafkaTemplate<Object, Object> 
in configuration class
@Bean(name = "InternalKafkaProducer")
    public KafkaTemplate<Object, Object> getKafkaTemplate() {
        final Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootStrapServer);
        properties.put("security.protocol", securityProtocol);
        properties.put("sasl.mechanism", saslMechanism);
        properties.put("sasl.jaas.config", saslJaasConfig);
        properties.put("sasl.login.callback.handler.class", saslOauthCallbackClass);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        final KafkaTemplate<Object, Object> template = new KafkaTemplate<Object, Object>(new DefaultKafkaProducerFactory<>(properties));
        template.setProducerListener(new KafkaProducerListener("InternalKafkaProducer", template));
        return template;
  }

【讨论】:

    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 2016-10-31
    相关资源
    最近更新 更多