![](/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.