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

大憨熊 提交于 2020-01-03 04:26:24

问题


I'm currently developing a Spring server application using Spring Boot.

I need to develop a system where some InputStream will be sent from either the local File System, or from FTP, or some other source to specific InputStreamConsumer instances, all this configured in database. The InputStreamConsumer already are managed beans.

My InputStreamProviders are likely to be Prototype beans. They will not be used by other beans, but they'll need to use a TaskScheduler and periodically send InputStreams to their InputStreamConsumers.

Long story short, I need to instantiate a list of Beans from external configuration using Spring. Is there a way to do that?


回答1:


OK, thanks to the link @Ralph mentioned in his comment (How do I create beans programmatically in Spring Boot?), I managed to do what I wanted to.

I'm using a @Configuration class InputStreamProviderInstantiator implements BeanFactoryAware.

The post didn't mention how to process the @Autowire annotations in the InputStreamProvider instances, though, so I'm posting here how to do it :

@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.
         }
    }
}


来源:https://stackoverflow.com/questions/28714426/spring-boot-create-a-list-of-managed-prototype-beans-from-database-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!