user439407
user439407

Reputation: 1756

Using ObjectFactory in Spring 5 to instantiate a list of prototype objects

In Spring 5 I am trying to find a list of classes that implement a particular interface, instantiate them, do some stateful processing, then repeat the process resetting the state. If didn't have to repeat the process inside a single method call I could just use prototype scoped classes and every time the method was called I would get a new object. And if it was just one object I could use ObjectFactory to create new instances, but how can I create a list of objects that implement a particular interface using ObjectFactory?

Code would look something like this:

  ObjectFactory<WidgetInterface> objectFactory = ...  
  while(hasMoreData()) {
        List<WidgetInterface> newWidgets = objectFactory.instantiateObjects()
        newWidgets.forEach(//do logic)

Upvotes: 1

Views: 882

Answers (2)

user8448548
user8448548

Reputation: 21

My version is 5.1.6, using ObjectProvider, it extends ObjectFactory and Iterable.

Upvotes: 2

Martin Frey
Martin Frey

Reputation: 10075

I think ObjectFactory gives you a new instance each time if the bean is a prototype.

You can just autowire the ObjectFactory and call getObject().

Upvotes: 0

Related Questions