@ConditionalOnBean(KafkaTemplate.class) crashes entire application

Viewed 104

I have a Spring boot application that consumes data from Kafka topic and send email notifications with a data received from Kafka,

@Bean
public EmailService emailService() {
    return new EmailServiceImpl(getJavaMailSender());
}

it works perfectly, but after I added @ConditionalOnBean:

@Bean
@ConditionalOnBean(KafkaTemplate.class)
public EmailService emailService() {
    return new EmailServiceImpl(getJavaMailSender());
}

application failed to start:

required a bean of type 'com.acme.EmailService' that could not be found.

And I can't find any explanation, how it is possible, because KafkaTemplate bean automatically created by Spring in KafkaAutoConfiguration class.

Could you please give me an explanation?

1 Answers

From the documentation:

The condition can only match the bean definitions that have been processed by the application context so far and, as such, it is strongly recommended to use this condition on auto-configuration classes only. If a candidate bean may be created by another auto-configuration, make sure that the one using this condition runs after.

This documentation clearly says what might be wrong here. I understand KafkaTemplateConfiguration creates the KafkaTemplate.class. But it may not be added in the bean context while the condition was being checked. Try to use autoconfiguration for KafkaTemplate or make sure the ordering of different configuration classes so that you can have the guarantee of having the KafkaTemplate in bean registry before that conditional check.

Related