【问题标题】:Dependency Injection by type using generics - how does it work?使用泛型按类型进行依赖注入 - 它是如何工作的?
【发布时间】:2010-12-23 07:39:53
【问题描述】:

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

@Resource
private List<Foo> allFoos;

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

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

【问题讨论】:

  • 1) 类型擦除发生在编译时,不是在运行时; 2) 在字段和方法/构造函数参数声明中指定的所有类型都由编译器完全保存在字节码中,并且在运行时通过 Java 反射 API 可用。所以,Spring 通过从对应的java.lang.reflect.Field 对象中获取allFoos 字段的元素类型来做到这一点。

标签: java generics spring dependency-injection


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    相关资源
    最近更新 更多