Spring Boot从数据库配置创建托管原型bean的列表
我目前正在使用Spring Boot开发一个Spring服务器应用程序 我需要开发一个系统,其中一些InputStream将从本地文件系统、FTP或其他源发送到特定的InputStreamConsumer实例,所有这些都在数据库中配置。InputStreamConsumer已经是托管bean 我的InputStreamProviders可能是原型bean。其他bean不会使用它们,但它们需要使用TaskScheduler并定期向InputStream使用者发送InputStreamsSpring Boot从数据库配置创建托管原型bean的列表,spring,spring-bean,Spring,Spring Bean,我目前正在使用Spring Boot开发一个Spring服务器应用程序 我需要开发一个系统,其中一些InputStream将从本地文件系统、FTP或其他源发送到特定的InputStreamConsumer实例,所有这些都在数据库中配置。InputStreamConsumer已经是托管bean 我的InputStreamProviders可能是原型bean。其他bean不会使用它们,但它们需要使用TaskScheduler并定期向InputStream使用者发送InputStreams 长话短说,
长话短说,我需要使用Spring从外部配置实例化一个bean列表。有办法吗?好的,多亏了他评论中提到的@Ralph链接,我成功地做到了我想做的事 我正在使用@Configuration类InputStreamProviderInstallator实现BeanFactoryAware 不过,帖子没有提到如何在InputStreamProvider实例中处理@Autowire注释,因此我在这里发布了如何处理这些注释:
@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.
}
}
}
你为什么要把它做成春豆呢?顺便说一句,这是一个一般的Spring框架问题。InputStreamProvider实例将是文件使用者、rest控制器或任何可以检索输入流并将其推送到InputStreamConsumer的托管实例的对象。因此,其中一些需要向TaskScheduler注册任务。他们中的一些人需要其他的豆子。我希望它能由Spring自动管理,这样@Configuration InputStreamProviderFactory就不必现在处理所有依赖项。这就是为什么我想让它们成为SpringBean。你有没有尝试过用编程的方式来创建这些Bean?我不确定我是否正确地理解了您的用例,但是如果您的单例bean负责创建这些InputStreamProvider的实例,而不是试图使它们成为容器的一级公民,那可能会更好。TaskScheduler依赖项可以是创建提供程序实例的对象的依赖项。@Stephane Nicoll:并非所有InputStreamProvider子类型都需要TaskScheduler。在这些子类型中可能会有RESTController。我还不知道我必须创建什么样的InputStreamProvider,以及它们需要什么依赖关系。这就是为什么我希望它们是托管bean。我可能想错了。如果我没有找到解决这个问题的方法,我会考虑这个解决方案。