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.