Spring从超类注入集合

时间:2015-02-28 00:52:26

标签: spring inheritance collections dependency-injection

我有以下情况:

class Super{
    private List<String> someStringsThatWillBeDifferentForEveryInstancePerDerivedType;
}

@Component
class Derived1 extends Super{
    @Autowired
    private String name;
}

@Component
class Derived2 extends Super{
    @Autowired
    private Long configId;
}

我在xml中为每个派生类定义了一个不同的List作为Spring bean ...将它们称为listForDerived1listForDerived2如何将这些列表连接到我的派生类?我尝试了构造函数注入,但我似乎无法找到任何运气注入集合和其他deps。

1 个答案:

答案 0 :(得分:2)

您可以对@Qualifier使用构造函数注入。

class Super {
    private List<String> someStrings;

    public Super(private List<String> someStrings) {
        this.someStrings = someStrings;
    }
}

@Component
class Derived1 extends Super {
    @Autowired
    public Derived1(@Qualifier("listForDerived1") List<String> listForDerived1, OtherBean bean) {
        super(listForDerived1);
    }
}

@Component
class Derived2 extends Super {
    @Autowired
    public Derived1(@Qualifier("listForDerived2") List<String> listForDerived1, OtherBean bean) {
        super(listForDerived2);
    }
}

另见官方Spring文档:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-autowired-annotation-qualifiers