简体   繁体   English

spring 启动 rabbitmq RabbitTemplate 错误

[英]spring boot rabbitmq RabbitTemplate error

I am taking the error that "Could not autowire. No beans of 'RabbitTemplate' type found".我正在接受“无法自动装配。找不到'RabbitTemplate'类型的bean”的错误。 I normally try to autowired RabbitTemplate to my producer class but it gives like that error.我通常尝试将 RabbitTemplate 自动连接到我的制作人 class,但它给出了类似的错误。

i tried to solve creating bean in configuration file.我试图解决在配置文件中创建 bean 的问题。 but it did not work.但它没有用。

package com.example.rabbitmqexample.producer;

import com.example.rabbitmqexample.model.Notification;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class NotificationProducer {

    @Value("${sr.rabbit.routing.name}")
    private String routingName;

    @Value("${sr.rabbit.exchange.name}")
    private String exchangeName;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendToQueue(Notification notification){
        System.out.println("Notification Sent ID: "+notification.getNotificationId());
        rabbitTemplate.convertAndSend(exchangeName,routingName,notification);
    }
}

As exception suggest there is no instance of RabbitTemplate with in IOC container, thus it can not be inject on other bean declarations like 'NotificationProducer' class.作为异常建议在IOC容器中没有RabbitTemplate的实例,因此它不能注入其他 bean 声明,如 'NotificationProducer' class。

You said你说

i tried to solve creating bean in configuration file.我试图解决在配置文件中创建 bean 的问题。 but it did not work.但它没有用。

Solution解决方案

proper bean declaration for RabbitTemplate , with respecting constructor and dependent bean binding they are many ways to do that. RabbitTemplate的正确 bean 声明,关于构造函数和依赖 bean 绑定,它们有很多方法可以做到这一点。 one practice to proper bean declaration with ConnectionFactory as a dependent bean for RabbitTemplate is as follow.ConnectionFactory作为RabbitTemplate的依赖 bean 的正确 bean 声明的一种做法如下。

@EnableRabbit
@Configuration
public class RabbitMQConfiguration {

    ...

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        //adding perhaps some extra confoguration to template like message convertor. etc.
        ...
        return rabbitTemplate;
    }
}

Always check the version docs depending the artifact version you are using for compatibility.始终根据您使用的工件版本检查版本文档以确保兼容性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM