在运行时替换弹簧容器内的bean [英] Replace a bean inside the spring container during run-time
本文介绍了在运行时替换弹簧容器内的bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在Spring容器中定义了一个bean(例如BeanA),并且此bean被注入到对象中. (例如BeanAUser)
Suppose I define a bean (eg BeanA) inside the Spring container, and this bean is injected into an object. (eg BeanAUser)
在运行时,我可以使用另一个bean实例替换spring容器中的原始BeanA吗?还将这个新的bean实例重新注入BeanAUser以便替换原来的BeanA吗?
During run-time, can I use another bean instance to replace the original BeanA inside the spring container?? And also re-injects this new bean instance into BeanAUser in order to replace the original BeanA?
推荐答案
使用代理可以轻松实现.创建接口的委派实现,并切换要委派的对象.
It can be easily achieved using a proxy. Create a delegating implementation of your interface and switch object it is delegating to.
@Component("BeanA")
public class MyClass implements MyInterface {
private MyInterface target;
public void setTarget(MyInterface target) {
this.target = target;
}
// now delegating implementation of MyInterface methods
public void method1(..) {
this.target.method1(..);
}
..
}
这篇关于在运行时替换弹簧容器内的bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文