【发布时间】: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