What works
Suppose I have a definition for spring bean ArrayList:
<bean id="availableLanguages" class="java.util.ArrayList"> <constructor-arg> <bean class="java.util.Arrays" factory-method="asList"> <constructor-arg> <list> <value>de</value> <value>en</value> </list> </constructor-arg> </bean> </constructor-arg> </bean>
Now I can insert this into all kinds of beans, for example. eg:
@Controller class Controller { @Autowired public Controller(ArrayList<String> availableLanguages) {
This works great.
How will it break
However, if I change my controller to a small bit and use the List
type instead of ArrayList
as follows:
@Controller class Controller { @Autowired public Controller(List<String> availableLanguages) {
Then instead, I get a list of all beans of type String
, not the bean that I defined. However, I really want my list to be placed on an unmodifiable List, but this will only be possible if I lower my dependency to a list.
So far, a workaround has been found
The following XML file:
<bean id="availableLanguages" class="java.util.Collections" factory-method="unmodifiableList"> <constructor-arg> <bean class="java.util.Arrays" factory-method="asList"> <constructor-arg> <list> <value>de</value> <value>en</value> </list> </constructor-arg> </bean> </constructor-arg> </bean>
works together with this controller:
@Controller class Controller { @Autowired public Controller(Object availableLanguages) { List<String> theList = (List<String>)availableLanguages; } }
While this works, adding an extra type is ugly.
conclusions
I realized that there is special handling for collections in spring 4.2.5 (the latest version) , which seems to cause all the problems. This creates special behavior when a parameter is an interface that extends Collection
. That way, I can work around using Object
or a specific implementation as a parameter type.
Question
Is there a way to directly insert a list into a bean? How?