我尝试用SpringBoot学习RabbitMQ我创建了2个类: Receiver.java(这是一个POJO):
此课程将收到该消息。
public class Receiver {
private CountDownLatch latch = new CountDownLatch(1);
public void receiveMessage(String message) {
System.out.println("Received <" + message + ">");
latch.countDown();
}
public CountDownLatch getLatch() {
return latch;
}
}
我的seconde类RabbitMq2Application.java(它是springBootApplication): 接收我的信息。
@SpringBootApplication
public class RabbitMq2Application implements CommandLineRunner{
final static String queueName = "spring-boot";
@Autowired
AnnotationConfigApplicationContext context;
@Autowired
RabbitTemplate rabbitTemplate;
@Bean
Queue queue() {
return new Queue(queueName, false);
}
@Bean
TopicExchange exchange() {
return new TopicExchange("spring-boot-exchange");
}
@Bean
Binding binding(Queue queue, TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(queueName);
}
@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(queueName);
container.setMessageListener(listenerAdapter);
return container;
}
@Bean
Receiver receiver() {
return new Receiver();
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
public static void main(String[] args) {
SpringApplication.run(RabbitMq2Application.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("Waiting five seconds...");
Thread.sleep(5000);
System.out.println("Sending message...");
rabbitTemplate.convertAndSend(queueName, "Hello from RabbitMQ!");
receiver().getLatch().await(10000, TimeUnit.MILLISECONDS);
context.close();
}
}
我收到此错误:org.springframework.beans.factory.NoSuchBeanDefinitionException
我怀疑这是因为他是@autowired。
答案 0 :(得分:0)
请分享更多StackTrace。通常,NoSuchBeanDefinitionException
周围有很多信息。
如果您导入正确的ConnectionFactory
课程,请从另一方面检查。那是因为你真的需要所有的bean(RabbitAutoConfiguration
):
@Autowired
private ConnectionFactory connectionFactory;
@Bean
@ConditionalOnMissingBean(RabbitTemplate.class)
public RabbitTemplate rabbitTemplate() {
return new RabbitTemplate(this.connectionFactory);
}
所需类型为:org.springframework.amqp.rabbit.connection.ConnectionFactory
。