【问题标题】:@ConditionalOnBean(KafkaTemplate.class) crashes entire application@ConditionalOnBean(KafkaTemplate.class) 使整个应用程序崩溃
【发布时间】:2021-08-11 23:20:21
【问题描述】:

我有一个Spring boot 应用程序,它使用来自Kafka 主题的数据,并使用从Kafka 收到的数据发送电子邮件通知,

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

完美运行, 但是在我添加@ConditionalOnBean之后:

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

应用程序启动失败:

需要一个 'com.acme.EmailService' 类型的 bean,它不能 找到了。

我找不到任何解释,这是怎么可能的,因为SpringKafkaAutoConfiguration类中自动创建了KafkaTemplate bean。

你能给我解释一下吗?

【问题讨论】:

    标签: java spring spring-boot apache-kafka spring-annotations


    【解决方案1】:

    来自documentation

    条件只能匹配已经被 到目前为止由应用程序上下文处理,因此,它是 强烈建议在自动配置中使用此条件 只上课。如果候选 bean 可能由另一个 自动配置,确保使用此条件的配置运行 之后。

    此文档清楚地说明了此处可能出现的问题。我了解KafkaTemplateConfiguration 创建KafkaTemplate.class。但在检查条件时,它可能不会添加到 bean 上下文中。尝试对KafkaTemplate 使用自动配置或确保不同配置类的顺序,以便在条件检查之前保证在bean 注册表中拥有KafkaTemplate

    【讨论】:

    • 添加到这里:如果您正在制作自己的自动配置,请添加 @AutoConfigureAfter(KafkaAutoConfiguration.class)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2017-11-10
    相关资源
    最近更新 更多