Issue
Some time ago i read about creating beans in Spring and there is an exception in creating bean for collections and maps. I mean to create a bean for collection or map, it is needed to create a wrapper class with for example a list as a field of this class
public class CollectionBean {
private List<String> someList;
}
and then it can be used in dependency injection. I wonder why it cannot be inject without wrapper class?
Solution
You can absolutely create beans that are collections:
public class CollectionsBean {
@Autowired
private List<String> nameList;
public void printNameList() {
System.out.println(nameList);
}
}
@Configuration
public class CollectionConfig {
@Bean
public CollectionsBean getCollectionsBean() {
return new CollectionsBean();
}
@Bean
public List<String> nameList() {
return Arrays.asList("John", "Adam", "Harry");
}
}
What might be causing confusion is that Java drops the generic part of a type at compilation. So Spring can't look at an object at runtime and know whether it's a List<String>
or a List<Integer>
-- to Java and Spring, at runtime, it's just a List
.
This means that type-based autowiring won't work, when there's more than one bean of type List
.
One way to get around this is to create a wrapper class, as you have done. Another way is to use one of the many other ways of disambiguating autowiring -- for example by name.
Answered By - slim