【问题标题】:Do we need to create bean for all in-built classes in Spring Boot?我们是否需要为 Spring Boot 中的所有内置类创建 bean?
【发布时间】:2020-07-11 18:50:14
【问题描述】:

我正在尝试使用 Spring Boot 配置 RabbitMQ。下面是我的配置类的快照。

案例一:

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

这段代码运行良好。

代码 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;
        }

但是,在这种情况下,如果我使用第 1 行,我正在创建 Jackson2JsonMessageConverter 的对象,则代码可以正常工作。

但我编写此代码是为了了解已经存在的代码的工作原理,其中使用了第 2 行而不是第 1 行。因此,当我使用第 2 行而不是第 1 行时,出现错误:

考虑在你的配置中定义一个 'org.springframework.amqp.support.converter.MessageConverter' 类型的 bean。

所以我有两个问题:

  1. 为什么会出现这个错误?
  2. 如果我为 MessageConverter 定义一个 bean,比如说

    @豆 公共 MessageConverter createMessageConverter() { 返回新的 Jackson2JsonMessageConverter(); }

然后就可以了。那为什么不要求我为 ConnectionFactory 参数定义一个 bean?

PS:这里没有使用@Autowired,也没有在我试图理解的代码中使用,ConnectionFactory 和 MessageConverter 这两个参数都是接口而不是类

【问题讨论】:

    标签: java spring spring-boot rabbitmq spring-rabbit


    【解决方案1】:

    简短的回答是:您需要了解 Spring Boot 中 AutoConfiguratris 的概念,它会为您创建很多 @Beans,而您不会“看到它们”。

    了解 AutoConfigurations 的一篇非常好的文章是这样的:

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

    在您的情况下,您可能还想查看 Spring Boot 源代码中的“RabbitAutoConfiguration”类。

    【讨论】:

    • 嘿,伙计...我是 YouTube 订阅者...很棒的视频...您的 Spring Boot 视频中是否更详细地解释了这个概念?
    • 谢谢 :) 我没有把我所有的 Spring Boot 视频都放到 YouTube 上,有人说我在解释它——但它是用德语的。试一试这篇文章,它试图以非常简单的方式解释它,并且是最新的。希望有帮助!
    • 我读过这篇文章。解开了我的疑惑。其实有一个父spring-boot项目,其配置中包含MessageConverter Bean的定义。这个项目被添加到 pom 中,它的配置包含在当前项目的配置中,使用 @Import。非常感谢。
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2020-01-12
    • 2022-01-06
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多