2015-12-04 64 views
0

我試圖想出一種在應用程序啓動後動態添加spring bean的方法。在運行時添加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取決於後處理器登記單後豆不觸發。我無法在這裏強制刷新。

有沒有辦法解決這個雞蛋問題?

回答

1

請參閱AutowireCapableBeanFactory.initializeBean(beanName)

您需要確保註冊和初始化之間沒有使用bean。

另外,請注意,在上下文初始化後註冊單例直到最近才真正是線程安全的(4.2.2,我認爲)。如果其他代碼在工廠中遍歷bean,則可能會導致ConcurrentModificationExceptions

但是,在這種情況下,註冊HTTP路徑可能爲時已晚,您可能需要更多代碼才能完成此操作。