使用泛型的类型依赖注入 - 它是如何工作的?

时间:2009-12-04 16:38:27

标签: java generics spring dependency-injection

使用Spring,我可以获得当前使用它定义的某种类型的所有bean:

@Resource
private List<Foo> allFoos;

Spring如何做到这一点?我认为泛型的类型信息在运行时被删除了。那么Spring如何知道列表的类型Foo并且只注入正确类型的依赖项?

为了说明:我没有包含其他bean的“List”类型的bean。相反,Spring创建该列表并将所有正确类型的bean(Foo)添加到此列表中,然后注入该列表。

1 个答案:

答案 0 :(得分:5)

并非所有通用信息都在运行时丢失:

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class Main {

    public static List<String> list;

    public static void main(String[] args) throws Exception {
        Field field = Main.class.getField("list");
        Type type = field.getGenericType();

        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Type[] types = pType.getActualTypeArguments();
            for (Type t : types) {
                System.out.println(t);
            }
        } else {
            System.err.println("not parameterized");
        }
    }

}

输出:

class java.lang.String
相关问题