问题
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