Using the factory instance method to dynamically prototype beans

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!

+6
source share
1 answer

I think that you say that you have a factory that is singleton, and you want it to create new objects each time you want a new one with a full dependency injection. The old way to do this is the Injection method that you refer to above. A new (and possibly cleaner) way is to use Scoped Proxy. You can use annotations or regular configuration , but the idea is that you are creating a proxy server around the bean (e.g. InnerObject). When you need a link to it, spring will automatically provide you with a new copy with the corresponding nested dependencies.

+2
source

Source: https://habr.com/ru/post/885860/


All Articles