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

Tho*_*zer 1 java generics spring dependency-injection

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

@Resource
private List<Foo> allFoos;
Run Code Online (Sandbox Code Playgroud)

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

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

sfu*_*ger 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");
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

class java.lang.String
Run Code Online (Sandbox Code Playgroud)