Reputation: 656
I want to integrate rabbitmq with my spring application. So, I added following lines inside my pom.xml
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
Then I Created a service called RabbitMessageService,
@Component
public class RabbitMessageService{
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage(String message) {
rabbitTemplate.convertAndSend("testExchange","testKey",message);
}
}
The problem is, RabbitTemplate @Autowire annotation is not working and rabbitTemplate is getting null when I call this method from another controller.
RabbitMessageService.sendMessage("Hello rabbit");
What I am missing. is the pom file looks correct with this repository or I need anything else to import? There are so many repository so I am confused which one should I import? And why autowiring is giving null here? I tried to initialize with get set but still the send method does not work(probably manually need to set connection properties but not sure how to do it)
Upvotes: 0
Views: 1836
Reputation: 8404
Spring Boot autoconfigures the RabbitTemplate
for you. If you are using plain vanilla Spring, you should define the RabbitTemplate
as a bean in your ApplicationContext
.
@Configuration
@EnableRabbit // Enable @RabbitListener support
public class RabbitConfig {
@Bean
public ConnectionFactory connectionFactory() {
return new CachingConnectionFactory("localhost");
}
@Bean
public AmqpAdmin amqpAdmin() {
return new RabbitAdmin(connectionFactory());
}
@Bean
public RabbitTemplate rabbitTemplate() {
return new RabbitTemplate(connectionFactory());
}
}
Upvotes: 1