1

I am using @KafkaListener in my application that's why I am using

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

My class using @Autowired @Qualifier("someName") for configuration while writing test class configuration which is Qualified with "someName" not loading..

so that it's throwing below error

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestTemplate'


available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=someName)}

Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73
Code Kida
  • 11
  • 1

1 Answers1

0

In such case main problem is @Bean("someName") not loading in spring container so while create the bean, hack the configuration which is return under @Bean("someName") for ex..

@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;
  }
Code Kida
  • 11
  • 1