
Originally Posted by
Thomas Matzner
Thanks for the hint, Costin, but that's the trick I'm missing somehow. All the examples I see inject values into singletons, at startup time. I'd need to declare an inject that should be done implicitly everytime a C instance is created during runtime.
So you have an object C that is not a singleton, and it depends on some bean (that is a singleton)?
One solution is creating a C factory, example:
Code:
class CFactory{
SomeDao _someDao;
CFactory(SomeDao someDao){
_someDao = someDao;
}
C void create(){
return new C(_someDao);
}
}
class ObjectThatNeedsC{
private CFactory _cfactory;
ObjectThatNeedsC(CFactory cfactory){
_cfactory = cfactory;
}
void someOperation(){
C c = _cfactory.create();
..do you stuff
}
}
And Spring code:
Code:
<bean id="someDao" class="SomeDao"/>
<bean id="cFactory" class="CFactory">
<constructor-arg ref="someDao"/>
</bean>
<bean id="someObjectThatNeedsC" class="SomeObjectThatNeedsC">
<constructor-arg ref="cFactory"/>
</bean>
You could also have a look at:
method injection
I don`t know how to feel about method injection. You have possibility to add some kind of behaviour (that can access the Spring context) to a class and the class won`t depend on Spring (it doesn`t need any imports) but the class has some strange semantics. That is why I don`t use method-injection (it could be that I`m missing something but at moment I would rather use a factory than method injection).