Do we need to create bean for all in-built classes in Spring Boot?

Rajyawardhan Singh Panwar :

I am trying to configure RabbitMQ with Spring Boot. Below is a snapshot of my config class.

Case 1:

   @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());            
        return template;
    }

This code works fine.

Code 2:

       @Bean
        public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter messageConverter) {
            RabbitTemplate template = new RabbitTemplate(connectionFactory);
    //      template.setMessageConverter(new Jackson2JsonMessageConverter()); // Line 1 - works
   //       template.setMessageConverter(messageConverter); // Line 2 - error: asks to inject Bean
            return template;
        }

In this case however, code works fine if I use the Line 1, where I am creating object of Jackson2JsonMessageConverter.

But I am writing this code to understand the working of an already existing code where instead of line 1, line 2 is used. So, when I use line 2 instead of line 1, I get error:

Consider defining a bean of type 'org.springframework.amqp.support.converter.MessageConverter' in your configuration.

So I have 2 questions:

  1. Why this error?
  2. If I define a bean for MessageConverter, say

    @Bean public MessageConverter createMessageConverter() { return new Jackson2JsonMessageConverter(); }

then it works. Then why is it not asking me to define a bean for ConnectionFactory argument?

PS: There are no @Autowired used, neither here, nor in the code I am trying to understand and both arguments, ConnectionFactory & MessageConverter are interfaces and not classes

Marco Behler :

The short answer is: You need to understand the concept of AutoConfiguratrions in Spring Boot, which will create a lot of @Beans for you, without you "seeing them".

A very good article to understand AutoConfigurations is this:

https://www.marcobehler.com/guides/spring-boot

In your case, you also might want to have a look at the "RabbitAutoConfiguration" class from Spring Boot's source code.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374448&siteId=1