字段 kafkaTemplate in ... 需要一个无法找到的类型为“org.springframework.kafka.core.KafkaTemplate”的 bean

时间:2021-05-04 21:11:22

标签: spring-boot spring-kafka

在将其标记为重复之前,请注意我已经查看了其他具有类似错误的堆栈溢出链接,但他们的解决方案在这种情况下实际上不起作用。

我想做什么: 我想将一个常规的旧 java 对象发送到 kafka 队列,以便我可以将它用作另一个服务中的事件。

好像坏了: 我正在关注互联网上的所有示例,所有这些示例都导致找不到 bean。也许示例已经过时,我错过了什么?

我有以下配置类:

@Configuration
@EnableKafka
public class KafkaProducerConfig {
    @Bean
    public ProducerFactory<String, NotificationEvent> producerFactory() {
        Map<String, Object> configProps = new HashMap<>();
        configProps.put(
                ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
                "localhost:9092");
        configProps.put(
                ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                StringSerializer.class);
        configProps.put(
                ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                JsonSerializer.class);
        return new DefaultKafkaProducerFactory<>(configProps);
    }

    @Bean
    public KafkaTemplate<String, NotificationEvent> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}

我也有这个 kafka 发送者类:

@Service
public class KafkaSender {

    @Autowired
    private KafkaTemplate<String,NotificationEvent> kafkaTemplate;

    public void send(String kafkaTopic, NotificationEvent notification) {
        this.kafkaTemplate.send(kafkaTopic, notification);
    }
}

通知类:

@Data
@AllArgsConstructor
public class NotificationEvent {
    private String bucket;
    private String prefix;

    @Override
    public String toString() {
        return "User [bucket=" + bucket + ", prefix="
                + prefix + "]";
    }
}

实际错误输出:

Field kafkaTemplate in <Removed to keep things generic> required a bean of type 'org.springframework.kafka.core.KafkaTemplate' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

1 个答案:

答案 0 :(得分:0)

如果没有完整代码,我无法判断,但看起来您正在使用 lombok 并且它干扰了您的 spring 配置。如果您删除 all args 注释并替换为适当的构造函数注入,我想您会发现它有效。