lundi 11 février 2019

A dependency autowired correctly in constructor gets null later on automatically for same Service object with KafkaListener

@EnableKafka
@Configuration
public class KafkaConfiguration {
@Bean
public ConsumerFactory<String, String> consumerFactory() {
   //configurations
    return new DefaultKafkaConsumerFactory<>(config);
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory();
    factory.setConsumerFactory(consumerFactory());
    return factory;
}
}


@Service
public class KafkaConsumer {
private Dep dependency;

@Autowired
public KafkaConsumer(Dep dep){
this.dependency = dep;
}

@KafkaListener(topics = "Kafka_Example", containerFactory = "kafkaListenerContainerFactory")
public void consume(String message) {
    System.out.println("Consumed message: " + message);
}

The dependency is properly autowired when constructor is called. But later on when consume method is called by spring kafka listener then dependency is null. Both times the object of Kafka consumer is the same.
How is this possible?
But when I add another containerfactory provider method it works and the dependency is not null.

@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> customKafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory();
    factory.setConsumerFactory(consumerFactory());
    return factory;
}

using this as containerFactory works.

What changed?





Aucun commentaire:

Enregistrer un commentaire