在应用程序加载时创建 bean

Create beans on application load

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

  1. Spring : Create beans at runtime
  2. https://www.logicbig.com/tutorials/spring-framework/spring-core/bean-definition.html
  3. How do I create beans programmatically in Spring Boot?

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

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

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

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

but the only way to do it is by telling the context what type of class you want to generate and let Spring handle it itself

否;从 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);