Re-inject CDI bean if some injected property changed

你。 提交于 2019-12-25 03:03:01

问题


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:

  1. Leave the "bean" as is. (So it will serve as Singleton).
  2. add a method in the bean: getConnection()
  3. When the property changes, recreate a new connection inside that bean.
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!