问题
I have a bean BeanA with injected property private int url
:
class BeanA { @Value(${"db.url"}) private String url; private DbConnection connection; }
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.
回答1:
If you don't use spring at all, I suggest:
- 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.
OR
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.
来源:https://stackoverflow.com/questions/55271965/re-inject-cdi-bean-if-some-injected-property-changed