I have a situation where I would like to dynamically create an object through a factory object, but the object must be created through the spring context in order to allow automatic connection of dependencies. I know that there are many other ways to solve this problem - for example, using the service locator pattern, but I would like to do this if possible.
Imagine that I have two objects:
class OuterObject { List<InnerObjectInterface> innerObjs; ... } class InnerObject implements InnerObjectInterface{ @Autowired SomeDependency someDependency; ... }
I want to create a factory that does something line by line:
class OuterObjectFactory { private innerObject = new InnerObject(); public OuterObject construct(params){ OuterObject o = new OuterObject(); List<InnerObjectInterface> inners = new ArrayList<InnerObjectInterface>(); ... for(some dynamic condition){ ... inners.add(createInnerObject()); ... } } public createInnerObject(){ return innerObject; } }
My spring -context.xml will look something like this:
<bean id="outerObjectFactory" class="path.OuterObjectFactory" /> <bean id="innerObject" class="path.InnerObject" factory-bean="outerObjectFactory" factory-method="createInnerObject" />
This, however, does not work. Only one innerObject is created where I want it to act as if it has a scope = "prototype". If I add scope = "prototype" to the bean definition:
<bean id="innerObject" class="path.InnerObject" factory-bean="outerObjectFactory" factory-method="createInnerObject" scope="prototype"/>
Then many internal objects are created, but they are not correctly connected. My colleague believes that the documentation found here implies that the factory bean is only used to initialize the bean, but I do not find this obvious.
I would appreciate it if someone could clarify my understanding here and maybe even suggest a better way to model a factory wired template than what I am doing.
Thanks!
source share