Spring autowire a list

半腔热情 提交于 2019-12-28 05:17:08

问题


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>();

回答1:


Spring 4 supports the ability to automatically collect all beans of a given type and inject them into a collection or array.

Example:

@Component
public class Car implements Vehicle {
}

@Component
public class Bus implements Vehicle {
}

@Component
public class User {
   @Autowired
   List<Vehicle> vehicles;//contains car and bus
}

Ref: Spring 4 Ordering Autowired Collections




回答2:


@Qualifier("..") is discouraged, instead try to autowire-by-name using

private @Resource(name="..") List<Strings> mimeTypes;

See also How to autowire factorybean.




回答3:


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 :

 <!-- creates a java.util.List instance with the supplied values -->
 <util:list id="emails">
   <value>pechorin@hero.org</value>
   <value>raskolnikov@slums.org</value>
   <value>stavrogin@gov.org</value>
   <value>porfiry@gov.org</value>
 </util:list>

So this would change your wiring to:

 @Autowired
 @Qualifier("emails")
 private List<String> mimeTypes = new ArrayList<String>();

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?




回答4:


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.




回答5:


If the autowired bean is declared in the same (@Configuration) class and you need it to declare another bean, then following works:

@Bean
public BeanWithMimeTypes beanWithMimeTypes() {
    return new BeanWithMimeTypes(mimeTypes());
}

@Bean
public List<String> mimeTypes() {
    return Arrays.<String>asList("text/html", "application/json);
}

Naturally it behaves correctly even if you override the mimeTypes bean in another config. No need for explicit @Qualifier or @Resource annotations.




回答6:


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



来源:https://stackoverflow.com/questions/6267138/spring-autowire-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!