如何重新初始化Spring Bean? [英] How to reinitialize a Spring Bean?

查看:3316
本文介绍了如何重新初始化Spring Bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时重新初始化Spring Bean?

Is it possible to reinitialize a Spring Bean on runtime?

我的Bean使用静态设置,在某些情况下会更改,然后我必须重新初始化Bean.

My Bean uses static settings which in some cases changes and then i have to reinitialize the bean.

推荐答案

在弹簧上下文中,您有三种选择来更新单例bean,您可以选择一种适合您的用例:

You have three options to update singleton bean in spring context, you can chose one suitable for your use case:

在Bean中重新加载方法
在您的bean中创建一个方法,该方法将更新/重新加载其属性.根据触发器,从spring上下文访问Bean,然后调用reload方法更新Bean属性(自单例以来),该属性也将在spring上下文中进行更新.自动接线/注入的任何地方.

Reload method In the Bean
Create a method in your bean which will update/reload its properties. Based on your trigger, access the bean from spring context, and then call the reload method to update bean properties (since singleton) it will also be updated in spring context & everywhere it is autowired/injected.

删除&在注册表中注册Bean
您可以使用DefaultSingletonBeanRegistry删除&重新注册您的bean.唯一的缺点是,它不会刷新/重新加载使用者类中已经自动接线/注入的Bean的旧实例.

Delete & Register Bean in Registry
You can use DefaultSingletonBeanRegistry to remove & re-register your bean. The only drawback to this, it will not refresh/reload old instance of already autowired/injected bean in consumer classes.

DefaultSingletonBeanRegistry registry = (DefaultSingletonBeanRegistry) context.getBeanFactory();
registry.destroySingleton({yourbean}) //destroys the bean object
registry.registerSingleton({yourbeanname}, {newbeanobject}) //add to singleton beans cache

@RefreshScope
对于从配置更改中刷新bean值属性很有用.但是它具有非常有限的&特定用途. 资源以获得更多信息.

这篇关于如何重新初始化Spring Bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆