我的情况是,我有一个属性文件来配置未知数量的 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() {
}
}
这工作得很好。然而,现在我想基于此创建 bean。到目前为止我尝试过的是
-
add @Bean
- 方法并从中调用它们postConstruct()
@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()
.
a BeanFactoryPostProcessor
or a BeanDefinitionRegistryPostProcessor
。但是,在这里我无权访问属性文件或RssConfig
-bean 来自上面,因为它在生命周期中调用得太早。
我需要做什么来生成这些动态数量的 bean?我可能只差那么一小步...我更喜欢 Java 配置解决方案而不是 XML 解决方案。
您需要注册 bean 定义(而不是调用@Bean
方法),所以BeanDefinitionRegistryPostProcessor
or ImportBeanDefinitionRegistrar
是目前做到这一点的最佳方法。您可以获取属性文件并使用绑定到它PropertiesConfigurationFactory
(在 Spring Boot 中)而不是使用@ConfigurationProperties
,或者也许您可以使用父上下文或独立的上下文SpringApplication
创建并绑定您的RssConfig
在你的 bean 定义注册代码中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)