【问题标题】:Spring adding beans at runtimeSpring在运行时添加bean
【发布时间】: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 后未触发的后处理器。我真的不能在这里强制刷新。

有没有办法解决这个鸡蛋问题?

【问题讨论】:

    标签: spring spring-integration


    【解决方案1】:

    AutowireCapableBeanFactory.initializeBean(beanName)

    您需要确保在注册和初始化之间没有使用 bean。

    另外,请注意,在上下文初始化后注册单例直到最近才真正线程安全(我认为是 4.2.2)。如果其他代码在工厂中的 bean 上迭代,它可能会导致 ConcurrentModificationExceptions

    但是,在这种情况下,注册 HTTP 路径可能为时已晚,您可能需要更多代码才能做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-20
      • 2016-04-18
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      相关资源
      最近更新 更多