按类型列出春季豆类


问题内容

在Spring中,有没有一种方法可以自动用一个类型及其所有子类型的bean填充列表?我有一个setter方法,如下所示:

setMyProp(List<MyType> list)

我想在MyType的任何bean和MyType的所有子类中自动装配。

谢谢杰夫


问题答案:

是的,您可以这样做。春天的文档说:

通过将注释添加到需要该类型数组的字段或方法中,也可以从ApplicationContext提供特定类型的所有bean。

请注意,它说您需要一个数组,而不是一个列表。这是有道理的,因为通用类型擦除意味着列表可能在运行时不起作用。但是,请使用以下有效的单元测试:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean class="test.Test.TypeB"/>
    <bean class="test.Test.TypeC"/>
    <bean class="test.Test.TypeD"/>
</beans>

和这个单元测试:

package test;

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class Test {

    private @Autowired List<TypeA> 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 {}

}

所以正式来说,您应该自动布线TypeA[],而不是List<TypeA>,但是List很好用。