Spring 自动装配列表
是否可以将 @Autowired
与列表一起使用?
就像我有带有 mimetypes 的属性文件,在我的类文件中我有这样的东西
@Autowired
private List<String> mimeTypes = new ArrayList<String>();
Is it possible to use @Autowired
with a list?
Like I have properties file with mimetypes and in my class file I have something like this
@Autowired
private List<String> mimeTypes = new ArrayList<String>();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Spring 4 及更早版本支持自动收集给定类型的所有 bean 并将它们注入到集合或数组中的功能。
这是一个示例:
参考:Spring 4 订购 Autowired 集合
Spring 4 and older support the ability to automatically collect all beans of a given type and inject them into a collection or array.
Here is an example:
Ref: Spring 4 Ordering Autowired Collections
不鼓励使用
@Qualifier("..")
,而是尝试使用 autowire-by-name另请参阅 如何自动装配factorybean。
@Qualifier("..")
is discouraged, instead try to autowire-by-name usingSee also How to autowire factorybean.
您甚至可以在 spring .xml 中创建一个 java.util.List 并通过 @Qualifier 将其注入到您的应用程序中。来自 springsource http://static.springsource.org/spring /docs/current/reference/xsd-config.html :
所以这会将您的接线更改为:
我建议采用这种方法,因为您无论如何都会注入字符串列表。
干杯!
编辑
如果您想注入属性,请查看此如何将属性值注入到使用注释配置的 Spring Bean 中?
You can even create a
java.util.List
within your spring .xml and inject this via@Qualifier
into your application. From the springsource http://static.springsource.org/spring/docs/current/reference/xsd-config.html :So this would change your wiring to:
I would suggest this approach since you're injecting a list of strings anyways.
cheers!
EDIT
If you want to inject properties, have a look at this How can I inject a property value into a Spring Bean which was configured using annotations?
我认为你至少需要一个限定符。而所谓的“新”似乎与使用Spring的理念相悖。你对 Spring 的角色感到困惑。如果你调用“new”,那么该对象就不受Spring的控制。
I think you'll need a qualifier at minimum. And the call to "new" seems contrary to the idea of using Spring. You have Spring's role confused. If you call "new", then the object isn't under Spring's control.
如果自动装配的 bean 在同一个 (
@Configuration
) 类中声明,并且您需要它来声明另一个 bean,则可以执行以下操作:即使您覆盖
mimeTypes 另一个配置中的 bean。不需要显式的
@Qualifier
或@Resource
注释。If the autowired bean is declared in the same (
@Configuration
) class and you need it to declare another bean, then following works:Naturally it behaves correctly even if you override the
mimeTypes
bean in another config. No need for explicit@Qualifier
or@Resource
annotations.只要列表是一个 bean,您就应该能够自动装配它。然后,您可以使用 @Qualifier 告诉 Spring 使用哪个 bean/列表。请参阅http://static。 springsource.org/spring/docs/3.0.x/reference/beans.html#beans-autowired-annotation-qualifiers
You should be able to autowire it as long as the list is a bean. You'd then use the
@Qualifier
to tell Spring which bean/list to use. See http://static.springsource.org/spring/docs/3.0.x/reference/beans.html#beans-autowired-annotation-qualifiers