Spring list beans by type-Collection of common programming errors
Yup, you can do this. The spring docs say:
It is also possible to provide all beans of a particular type from the ApplicationContext by adding the annotation to a field or method that expects an array of that type.
Note that it says you need to expect an array, not a list. This makes sense, because generic type erasure means a list may not work at runtime. However, take the following unit test, which works:
and this unit test:
package test;
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {
private @Autowired List beans;
@org.junit.Test
public void test() {
assertNotNull(beans);
assertEquals(2, beans.size());
for (TypeA bean : beans) {
assertTrue(bean instanceof TypeA);
}
}
public static interface TypeA {}
public static class TypeB implements TypeA {}
public static class TypeC extends TypeB {}
public static class TypeD {}
}
So officially, you’re supposed to autowire TypeA[]
, not List
, but the List works good.