开发者

Share java object between two forms using Spring IoC

开发者 https://www.devze.com 2022-12-28 17:07 出处:网络
I want to share java object between two forms using Spring IoC. It should acts like Registry: Registry.set(\"key\", new Object());

I want to share java object between two forms using Spring IoC. It should acts like Registry:

Registry.set("key", new Object());
// ...
Object o = Registry.get("key");
// ...
Registry.set("key", new AnotherObject()); // rewrite old object

I tried this code to register bean at runtime:

applicationContex开发者_如何学Got.getBeanFactory().registerSingleton("key", object);

but it does not allow to rewrite existing object (result code for checking and deleting existing bean is too complicated)...

PS I am Java newbie, so mb I am doing it wrong and I should not use IoC at all... any help is appreciated...


I don't know why you feel like you have to register the class at runtime. Why not just configure it in the factory and inject it like any other POJO?

Be careful with a shared registry like this. It's begging for thread safety. If you're new to Java, this is an area that fraught with peril.


It's possible to do what you want.

To register new bean instance you should use

org.springframework.beans.factory.config.SingletonBeanRegistry#registerSingleton

and before re-register object you should use

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#destroySingleton

to remove previously registered bean. Both of these metods are available in concrete BeanFactory implementations.

However, I think you're a bit misusing Spring while trying define dependencies in a runtime. Spring fits better for a declarative dependency management, and programmatic approach may overcomplicate things here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号