tags:

views:

80

answers:

2

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:

applicationContext.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...

+2  A: 

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.

duffymo
Also can leak memory, Too often stuff is added in and never taken out.
Romain Hippeau
I have to configure it at runtime (it depends on user input). So you recommend do not use IoC at all and manually inject it via setter/getter? I ask, because I use NetBeans GUI composer and I am not sure that it is good idea to add/modify code generated by NetBeans...
Vladimir
No, I don't understand it. Adding and removing things to registry is done at runtime, but injecting it into objects that need it is a configuration detail. Which one are you talking about?You probably shouldn't be using DI. If you're new to Java, I'd say it's an advanced topic that you should defer.
duffymo
I regularly recreate that object (it's much easier to recreate it than reconfigure it state), so as I understand I need to reinject it myself whenever I recreate it (now I use ctx.getBean("name") and want to replace object for bean "name"). Does it make sense?
Vladimir
No, I'm sorry, I'm not following you at all.
duffymo
A: 
wax