问题描述
我有一个具有注入属性 private int url
的bean BeanA:
I have a bean BeanA with injected property private int url
:
class BeanA { @Value(${"db.url"}) private String url; private DbConnection connection; }
让我们说这个 Value
注释是类似于Spring Value
。在初始化期间,将通过使用url字段中的注入属性来初始化连接。在 BeanA
中还有一些 PostConstruct和PreDestroy
方法。
我的问题是: url
属性更改后,是否可以动态地重新实例化 BeanA
。我有检测属性变化的机制。现在,我只重新注入该URL,但是我想重新创建此Bean,初始化新的连接,然后在所有Dependetn Bean中重新注入此Bean。我不使用Spring Cloud Config。
Let us say this Value
annotation is similar to Spring Value
. During initialization, connection will be initialized by using injected property into url field. And also there is some PostConstruct and PreDestroy
methods in BeanA
.My question is: is it possible to dynamically reinstantiate BeanA
when url
property changed. I have mechanism of detecting property change. For now, I just re-inject this url only, but I want to recreate this bean, initialize new connection and re-inject this bean in all dependetn beans. I dont use Spring Cloud Config.
推荐答案
如果您根本不使用spring,我建议:
If you don't use spring at all, I suggest:
- 将 bean保持不变。 (因此它将用作Singleton。)
- 在Bean中添加一个方法:getConnection()
- 属性更改时,重新创建一个新连接
- 任何需要连接的组件都将始终调用Bean的getConnection(),并且将始终获取最新的连接实例。
- Leave the "bean" as is. (So it will serve as Singleton).
- add a method in the bean: getConnection()
- When the property changes, recreate a new connection inside that bean.
- Any component that needs the connection will always call the bean's getConnection() and it will always get the most updated connection instance.
或
您可能希望使用代理设计模式来使用bean由客户端但在内部引用另一个连接Bean(目标 Bean),并且目标可以用全新的Bean的新实例代替。但是总是,客户端/用户对代理拥有相同的引用。
You might want to use a Proxy design pattern where your bean is used by the client but internally refers to another connection bean (the "target" bean) and the target may be replaced with a new instanse of a completely new bean. But always, the client/user holds the same reference to the proxy.
这篇关于如果某些注入的属性已更改,则重新注入CDI bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!