Spring 引导从数据库配置创建托管原型 bean 列表

Spring Boot create a list of managed prototype beans from database configuration

我目前正在使用 Spring Boot.

开发 Spring 服务器应用程序

我需要开发一个系统,其中一些 InputStream 将从本地 File System,或从 FTP,或其他来源发送到特定的 InputStreamConsumer 实例,所有这些在数据库中配置。 InputStreamConsumer 已经是托管 Bean。

我的 InputStreamProviders 很可能是 Prototype beans。它们不会被其他 bean 使用,但它们需要使用 TaskScheduler 并定期将 InputStreams 发送到它们的 InputStreamConsumers。

长话短说,我需要使用 Spring 从外部配置实例化 Beans 的列表。有办法吗?

好的,感谢 link @Ralph 在他的评论中提到 (How do I create beans programmatically in Spring Boot?),我设法做到了我想做的事。

我正在使用 @Configuration class InputStreamProviderInstantiator implements BeanFactoryAware

post 没有提到如何在 InputStreamProvider 实例中处理 @Autowire 注释,所以我 post 在这里介绍如何处理它:

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class InputStreamProviderInitializer implements BeanFactoryAware {

    private AbstractAutowireCapableBeanFactory factory;
    @Inject
    InputStreamProviderConfigurationRepository configurationRepository;

    @Override
    public void setBeanFactory(BeanFactory factory) {
        Assert.state(factory instanceof AbstractAutowireCapableBeanFactory, "wrong bean factory type");
        this.factory = (AbstractAutowireCapableBeanFactory) factory;
    }

    @PostConstruct
    private void initializeInputStreamProviders() {
         for (InputStreamProviderConfigurationEntity configuration : configurationRepository.findAll()) {
             InputStreamProvider provider = // PROVIDER CREATION, BLAH, BLAH, BLAH
             String providerName = "inputStreamSource"+configuration.getId();
             factory.autowireBean(provider);
             factory.initializeBean(source, providerName);
             factory.registerSingleton(providerName, source); // I don't think it's mandatory since the providers won't be called by other beans.
         }
    }
}