Home > database >  spring boot rabbitmq RabbitTemplate error
spring boot rabbitmq RabbitTemplate error

Time:11-29

I am taking the error that "Could not autowire. No beans of 'RabbitTemplate' type found". I normally try to autowired RabbitTemplate to my producer class but it gives like that error.

i tried to solve creating bean in configuration file. but it did not work.

`

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);
    }
}

`

CodePudding user response:

As exception suggest there is no instance of RabbitTemplate with in IOC container, thus it can not be inject on other bean declarations like 'NotificationProducer' class.

You said

i tried to solve creating bean in configuration file. but it did not work.

Solution

proper bean declaration for RabbitTemplate, with respecting constructor and dependent bean binding they are many ways to do that. one practice to proper bean declaration with ConnectionFactory as a dependent bean for RabbitTemplate is as follow.

@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;
    }
}

Always check the version docs depending the artifact version you are using for compatibility.

  • Related