2009-12-04 66 views
1

使用Spring,我可以得到使用此当前定义的某种类型的所有豆类:依类型使用泛型的依赖注入 - 它是如何工作的?

@Resource 
private List<Foo> allFoos; 

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

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

+0

1)类型的擦除发生在编译时,*不*在运行时; 2)在字段和方法/构造函数参数声明中指定的所有类型都由编译器完全保留在字节码中,并且在运行时通过Java Reflection API提供。所以,Spring通过从相应的java.lang.reflect.Field对象中获取'allFoos'字段的元素类型来完成它。 – 2015-08-23 17:08:01

回答

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