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

查看:149
本文介绍了如何重新初始化 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.

推荐答案

在 spring 上下文中更新单例 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.

删除 &在 Registry 中注册 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天全站免登陆