Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring autowire a list

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>(); 
like image 380
karq Avatar asked Jun 07 '11 14:06

karq


People also ask

How do I Autowire a list in spring?

In the spring boot, @Autowired injects object arrays and java collections. Java collections such as list, set, map, array are injected using the @Autowired annotation. Collections commonly used, such as ArrayList, HashMap, HashTable, HashSet, TreeHashMap, can be automatically wired using @Autowired on the spring boot.


2 Answers

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:

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

Ref: Spring 4 Ordering Autowired Collections

like image 62
Tho Avatar answered Sep 28 '22 04:09

Tho


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

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

See also How to autowire factorybean.

like image 39
Johan Sjöberg Avatar answered Sep 28 '22 03:09

Johan Sjöberg