如何在Spring中注入List的实例? [英] How can I inject an instance of List in Spring?
问题描述
假设我有一个ArrayList的spring bean定义:
Suppose I have a spring bean definition of an 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 inject this into all kinds of beans, e.g. like this:
@Controller
class Controller {
@Autowired
public Controller(ArrayList<String> availableLanguages) {
// ...
}
}
这很好用.
但是,如果我稍稍更改控制器并使用类型List
代替ArrayList
,则是这样的:
However if I change my controller a tiny bit and use the type List
instead of ArrayList
like this:
@Controller
class Controller {
@Autowired
public Controller(List<String> availableLanguages) {
// ...
}
}
然后我得到的是所有类型为String
的bean的列表,而不是我定义的bean.但是我实际上是想将我的列表包装到一个不可修改的列表中,但是只有当我将依赖项降级为列表时,这才有可能.
Then instead I get a list of all beans of type String
rather then the bean I defined. However I actually want to wrap my List into an unmodifiable List, but this will only be possible if I downgrade my dependency to a list.
以下XML文件:
<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>
与此控制器一起工作:
@Controller
class Controller {
@Autowired
public Controller(Object availableLanguages) {
List<String> theList = (List<String>)availableLanguages;
}
}
虽然可行,但额外的类型转换很难看.
While this works the extra type cast is ugly.
I figured that there is a special handling for collections in Spring 4.2.5 (the currently most recent version) which seems to cause all the trouble. It creates special behaviour when a parameter is an interface that extends Collection
. Thus I can workaround by using Object
or a concrete implementation as parameter type.
有什么方法可以将列表直接注入到bean中吗?怎么样?
Is there any way to directly inject a list into a bean? How?
推荐答案
使用@Qualifier将给定的限定符注入bean.您可以命名要成为Bean的列表,这样可以很好地工作.
Using @Qualifier will inject the bean with the given qualifier. You can name the list which you want to be a bean and that will work fine.
这篇关于如何在Spring中注入List的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!