Spring FactoryBean - iterating over an "object creation" list
Santa's got a list. He wants to make a "present" for every child on hist list (we're assuming for the moment they're all good) and load them all in his sled. Can he do it with Spring?
I've wri开发者_如何学Gotten a simple FileListFactory that implements FactoryBean and returns a list of strings that represents the lines in a given file. Set that aside for now - if we solve the problem for a <list>, then I assume I can plug in a ref to this factory's output in its place.
What I want is a list of "foo" objects. The foo objects are non-singleton instances of some bean (likely with an abstract bean definition). Each foo object created gets one of the list items as a property.
To up the ante one level further, the property in question is of a "bar" object. I have already created a property editor to make "bar" objects from strings. So the thing that iterates over the list of strings should use the property editor infrastructure when setting the per-instance property.
It seems like there ought to be some sort of list factory iterator bean or something for this. The problem appears to be that all of the searches I'm doing to look for example solutions to this fail because terms like "list" are far too generic.
If I understood you correctly, you have a list of strings (read from a file, for instance). For each of this strings you want to create a "foo" object where the given string is assigned to the "bar" property, with the appropriate conversion.
You can achieve this by implementing an own BeanFactoryPostProcessor
. For each of the strings, create a new BeanDefinition
and register it with the target factory. To simplify things, create and register a ChildBeanDefinition
, providing the name of the "parent" bean with all the generic configuration and only setting the "bar" property.
I never did come back and document what I wound up with.
The magic is that the factory object that iterates over the list is abstract. It has an abstract method that returns instances of "foo". In this case:
public abstract Foo createFoo();
Despite this being an abstract class, you create a concrete instance of it in the Spring XML config, but with an extra child node in the XML that looks like this:
<bean id="Santa" class="...">
<lookup-method name="createFoo" bean="fooFactory"/>
...
</bean>
And the "fooFactory" bean is a factory that vends Foo objects.
The net result is that, through the magic of Spring IoC, what you get is an anonymous object that is a concrete instantiation of the abstract class that includes an implementation of the abstract method that references the factory bean.
The Santa class code simply takes the List, iterates over it, calls createFoo() to get a Foo and then calls Foo.setBar() as appropriate.
Mischief managed!
精彩评论