【发布时间】:2015-12-04 17:42:10
【问题描述】:
我正在尝试想出一种在应用程序启动后动态添加 Spring bean 的方法。
我发现了几个地方有类似的问题,例如here
而且我知道 ApplicationContext 扩展点,例如 ApplicationContext 事件和 BeanFactoryPostProcessor。
我手头的问题是我需要在创建一些 bean 之后添加 bean,我猜这会丢弃 BeanFactoryPostProcessor 选项,因为它会在应用程序上下文开始注册 bean 之前发生。
我尝试在刷新上下文后添加一个 singletonBean:
@EventListener
public void postProcess(ContextRefreshedEvent refreshedEvent) throws BeansException {
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext)refreshedEvent.getApplicationContext()).getBeanFactory();
List<Api> apis = repository.findAll();
apis.forEach(api -> {
api.getEndpoints().forEach(endpoint -> {
HttpRequestHandlingMessagingGateway gateway = createGateway(endpoint);
customIntegrationHandlerMapping.register(gateway);
beanFactory.registerSingleton("httpflow-"+endpoint.getId(),createEndpointFlow(gateway));
});
});
}
问题在于 IntegrationFlow 依赖于注册单例 bean 后未触发的后处理器。我真的不能在这里强制刷新。
有没有办法解决这个鸡蛋问题?
【问题讨论】: