![](/img/trans.png)
[英]Spring AMQP Dynamically create RabbitTemplate and SimpleMessageListenerContainer, error RabbitTemplate is not configured as MessageListener
[英]spring boot rabbitmq RabbitTemplate error
我正在接受“无法自动装配。找不到'RabbitTemplate'类型的bean”的错误。 我通常尝试将 RabbitTemplate 自动连接到我的制作人 class,但它给出了类似的错误。
我试图解决在配置文件中创建 bean 的问题。 但它没有用。
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);
}
}
作为异常建议在IOC容器中没有RabbitTemplate
的实例,因此它不能注入其他 bean 声明,如 'NotificationProducer' class。
你说
我试图解决在配置文件中创建 bean 的问题。 但它没有用。
解决方案
RabbitTemplate的正确 bean 声明,关于构造函数和依赖 bean 绑定,它们有很多方法可以做到这一点。 将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;
}
}
始终根据您使用的工件版本检查版本文档以确保兼容性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.