【问题标题】:Create beans on application load在应用程序加载时创建 bean
【发布时间】:2020-11-16 10:47:03
【问题描述】:

在开始阅读之前,这是我为解决此问题而尝试阅读的链接列表:

  1. Spring : Create beans at runtime
  2. How to add bean instance at runtime in spring WebApplicationContext?
  3. https://www.logicbig.com/tutorials/spring-framework/spring-core/bean-definition.html
  4. Spring - Programmatically generate a set of beans
  5. How do I create beans programmatically in Spring Boot?

我正在使用 SpringBoot 和 RabbitMQ 提供服务,最近我读到了这篇文章:https://programmerfriend.com/rabbit-mq-retry/

我想概括一下这个想法并创建一个 SpringBoot 库,它可以通过application.properties 文件获取需要创建的队列的名称并在幕后完成所有操作,因此创建不同的队列和每当我将库集成到服务中时,它们之间的绑定就会“自动”发生。

我面临的问题基本上是@Bean 给我的行为相同。我需要多次重复此行为 N 次(与我的 application.properties 中指定的名称数量一样多)。

从我在网上看到的情况来看,有可能在加载应用程序时创建 bean,但唯一的方法是告诉上下文您要生成什么类型​​的类并让 Spring 自己处理。由于我要生成的类不包含默认构造函数(并且不受我控制),我想知道是否有办法创建一个对象并将这个特定实例添加到应用程序上下文中。

【问题讨论】:

    标签: spring-boot kotlin amqp spring-amqp


    【解决方案1】:

    但唯一的方法是告诉上下文你想生成什么类型​​的类,让 Spring 自己处理

    没有;从 5.0 开始,您现在可以为 bean 提供 Supplier

    /**
     * Register a bean from the given bean class, using the given supplier for
     * obtaining a new instance (typically declared as a lambda expression or
     * method reference), optionally customizing its bean definition metadata
     * (again typically declared as a lambda expression).
     * <p>This method can be overridden to adapt the registration mechanism for
     * all {@code registerBean} methods (since they all delegate to this one).
     * @param beanName the name of the bean (may be {@code null})
     * @param beanClass the class of the bean
     * @param supplier a callback for creating an instance of the bean (in case
     * of {@code null}, resolving a public constructor to be autowired instead)
     * @param customizers one or more callbacks for customizing the factory's
     * {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
     * @since 5.0
     */
    public <T> void registerBean(@Nullable String beanName, Class<T> beanClass,
            @Nullable Supplier<T> supplier, BeanDefinitionCustomizer... customizers) {
    

    所以

    context.registerBean("fooBean", Foo.class, () -> someInstance);
    

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多