【问题标题】:How can I reload specific application context bean dynamically?如何动态重新加载特定的应用程序上下文 bean?
【发布时间】:2018-06-18 03:14:32
【问题描述】:

我目前正在开发一个基于 JDK8 和 spring-beans:4.3.1.RELEASE 的基于 groovy 的应用程序。我需要介绍一种方法,通过该方法我可以在运行时通过其名称重新创建目标 bean。我做了这样的事情,但是当我@autowire特定的bean时,我当前的实现没有效果,在调用reload方法后,在应用程序运行时更改的属性不会反映在@autowired bean上。 context.refresh() 对我来说工作得很好,但它重新创建了整个 bean,这些 bean 最终过度杀伤了我的过程。所以基本上,我正在寻找一种方法,我可以通过它的名称重新加载特定的 bean。

@Autowired
ApplicationContext applicationContext

@Override    
public synchronized Map<String, ?> reloadBean(String beanName) {

    ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext

    def beanObject = context.getBean(beanName)

    /* Reload the properties file */
    reloadProperties()

    /* Bean factroy method call */
    beanObject.buildFromConfiguration()

    DefaultSingletonBeanRegistry defaultSingletonBeanRegistry = (DefaultSingletonBeanRegistry) context.getBeanFactory()

    /* Destroy the given bean. */
    defaultSingletonBeanRegistry.destroySingleton(beanName)

    if(!defaultSingletonBeanRegistry.containsSingleton(beanName)) {

        /* Add the given singleton object to the singleton cache of this factory. */
        defaultSingletonBeanRegistry.registerSingleton(beanName, beanObject)

        beanLoadStatus.put(beanName, "Application context bean reloaded successfully.")
    } else {
        beanLoadStatus.put(beanName, "Failed to release old application context bean.")
    }

    return beanLoadStatus
}

【问题讨论】:

    标签: spring groovy java-8 javabeans autowired


    【解决方案1】:

    你看过 RefreshScope 注释了吗?它可以通过对要刷新的 bean 更具选择性来帮助您。您可以在以下链接中查看:

    https://cloud.spring.io/spring-cloud-static/docs/1.0.x/spring-cloud.html#_refresh_scope

    根据参考(http://static.javadoc.io/org.springframework.cloud/spring-cloud-commons-parent/1.1.4.RELEASE/org/springframework/cloud/context/config/annotation/RefreshScope.html

    方便注释将@Bean 定义置于刷新范围内。以这种方式注释的 Bean 可以在运行时刷新,任何使用它们的组件都将在下一次方法调用时获得一个新实例,完全初始化并注入所有依赖项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-30
      • 2011-06-21
      相关资源
      最近更新 更多