提问者:小点点

使用属性文件的配置创建未知数量的Bean


我的情况是,我有一个属性文件来配置未知数量的bean:

rssfeed.source[0]=http://feed.com/rss-news.xml
rssfeed.title[0]=Sample feed #1
rssfeed.source[1]=http://feed.com/rss-news2.xml
rssfeed.title[1]=Sample feed #2
:

我有一个配置类来读取这些属性:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "rssfeed", locations = "classpath:/config/rssfeed.properties")
public class RssConfig {

  private List<String> source = new ArrayList<String>();
  private List<String> title = new ArrayList<String>();

  public List<String> getSource() {
    return source;
  }
  public List<String> getTitle() {
    return title;
  }

  @PostConstruct
  public void postConstruct() {

  }
}

这是很好的工作。然而,现在我想在此基础上创建beans。到目前为止我所尝试的是

>

  • 添加@Bean-方法并从postConsort()调用它们

      @Bean
      @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
      public SourcePollingChannelAdapter createFeedChannelAdapter(int id, String url) {
        SourcePollingChannelAdapter channelAdapter = new SourcePollingChannelAdapter();
        channelAdapter.setApplicationContext(applicationContext);
        channelAdapter.setBeanName("feedChannelAdapter" + id);
        channelAdapter.setSource(createMessageSource(id, url));
        return channelAdapter;
      }
    
      @Bean
      @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
      public FeedEntryMessageSource createMessageSource(int id, String url) {
        try {
          FeedEntryMessageSource messageSource = new FeedEntryMessageSource(new URL(url), "");
          messageSource.setApplicationContext(applicationContext);
          messageSource.setBeanName("feedChannelAdapter" + id + ".source");
          return messageSource;
        } catch (Throwable e) {
          Utility.throwAsUncheckedException(e);
          return null;
        }
      }
    
      @Bean
      @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
      public QueueChannel createFeedChannel(int id, String url) {
        QueueChannel channel = new QueueChannel();
        channel.setApplicationContext(applicationContext);
        channel.setBeanName("feedChannel" + id);
        return channel;
      }
    
      @PostConstruct
      public void postConstruct() {
        for (int x = 0; x < source.size(); x++) {
          createFeedChannelAdapter(x, source.get(x));
        }
      }
    

    然而,Spring尝试将参数自动关联到这些方法,而不是使用我在postConstruct()中提供的参数。

    BeanFactoryPostProcessorBeanDefinitionRegistryPostProcessor。但是,在这里我无法访问属性文件或上面的 RssConfig-bean,因为它在生命周期中被调用得太早了。

    我需要做什么来生成这些动态数量的bean?我可能只是一小步之遥……我更喜欢Java配置解决方案而不是XML解决方案。


  • 共1个答案

    匿名用户

    您需要注册 Bean 定义(而不是调用 @Bean 方法),因此 BeanDefinitionRegistryPostProcessorImportBeanDefinitionRegistrar 是目前执行此操作的最佳方法。你可以获取属性文件并使用 PropertiesConfigurationFactory(在 Spring Boot 中)而不是使用 @ConfigurationProperties 绑定到它,或者你可以使用父上下文或独立的 SpringApplication 在 Bean 定义注册代码中创建和绑定你的 RssConfig