The @RabbitListener annotation lets your Spring Boot app listen to messages from RabbitMQ queues automatically. It helps your app react when new messages arrive.
@RabbitListener for consuming in Spring Boot
import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class MessageListener { @RabbitListener(queues = "queueName") public void receiveMessage(String message) { // process the message } }
The @RabbitListener annotation marks a method to receive messages from the specified queue.
The method parameter usually matches the message payload type, like String or a custom object.
ordersQueue and prints the order message.@RabbitListener(queues = "ordersQueue") public void receiveOrder(String order) { System.out.println("Order received: " + order); }
@RabbitListener(queues = "emptyQueue") public void receiveEmptyQueue(String message) { System.out.println("Message from emptyQueue: " + message); }
@RabbitListener(queues = "singleMessageQueue") public void receiveSingleMessage(String message) { System.out.println("Single message: " + message); }
@RabbitListener(queues = "endQueue") public void receiveEndQueue(String message) { System.out.println("Last message in queue: " + message); }
This Spring Boot app listens to the RabbitMQ queue named testQueue. When a message arrives, it prints it to the console.
package com.example.rabbitlistenerdemo; import org.springframework.amqp.rabbit.annotation.EnableRabbit; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Component; @SpringBootApplication @EnableRabbit public class RabbitListenerDemoApplication { public static void main(String[] args) { SpringApplication.run(RabbitListenerDemoApplication.class, args); } } @Component class SimpleMessageListener { @RabbitListener(queues = "testQueue") public void receiveMessage(String message) { System.out.println("Received message: " + message); } }
Time complexity: Receiving a message is O(1) because it processes one message at a time.
Space complexity: Minimal, only stores the current message being processed.
Common mistake: Forgetting to enable Rabbit support with @EnableRabbit or missing queue configuration.
Use @RabbitListener when you want automatic, event-driven message consumption instead of manual polling.
@RabbitListener makes your app listen to RabbitMQ queues easily.
It runs the annotated method whenever a new message arrives.
Remember to enable Rabbit support and configure queues properly.