我动态创建SourcePollingChannelAdapter
。将新的url添加到db后,我创建SourcePollingChannelAdapter
的新实例并启动它。
这里的代码:
public SourcePollingChannelAdapter getAdapter(RssStream rssStream) throws MalformedURLException {
String beanIdAdapter = "adapter." + rssStream.getId();
String beanIdSource = "source." + rssStream.getId();
SourcePollingChannelAdapter adapter;
if (context.containsBean(beanIdAdapter)) {
adapter = (SourcePollingChannelAdapter) context.getBean(beanIdAdapter);
}
else {
URL url = new URL(rssStream.getLink());
FeedEntryMessageSource source = new FeedEntryMessageSource(url, "news");
source.setApplicationContext(context);
source.setBeanName("source");
source.setBeanFactory(beanFactory);
source.afterPropertiesSet();
adapter = new SourcePollingChannelAdapter();
adapter.setApplicationContext(context);
adapter.setBeanName(beanIdAdapter);
adapter.setBeanFactory(beanFactory);
adapter.setSource(source);
adapter.setOutputChannel(channel);
adapter.setTrigger(new PeriodicTrigger(5000));
adapter.afterPropertiesSet();
}
return adapter;
}
但是,从db中删除url之后,我需要停止并删除
SourcePollingChannelAdapter
。public void deleteAdapter(int id) {
final String beanId = "adapter." + id;
if (context.containsBean(beanId)) {
SourcePollingChannelAdapter adapter = (SourcePollingChannelAdapter) context.getBean(beanId);
adapter.stop(new Runnable() {
@Override
public void run() {
BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry) beanFactory;
beanDefinitionRegistry.removeBeanDefinition(beanId);
}
});
}
}
我创建新的适配器,将其启动,然后尝试删除。但是我得到了
NoSuchBeanDefinitionException
。如何解决这个问题呢? 最佳答案
您需要注册Bean
if (beanFactory instanceof ConfigurableListableBeanFactory) {
((ConfigurableListableBeanFactory) beanFactory).registerSingleton(
beanIdAdapter, adapter);
}
尽管框架这样做,但是您实际上并不需要注册源代码(除非您以后还需要访问它)。
编辑:
但是,该框架并非真正针对此活动而设计的-将引用保留在您自己的类中会更好。请参见this note。