spring如何知道在通用列表中注入什么?
给定那个代码片段spring如何知道在通用列表中注入什么?,spring,Spring,给定那个代码片段 @Service public class MapUnitsService { @Autowired private List<UnitMapping> unitMappings; ... @服务 公共类MapUnitsService{ @自动连线 私有列表映射; ... 既然类型信息在运行时消失了,spring如何知道向unitMappings注入什么呢?基本上,spring将在该类型的应用程序上下文中注入所有bean。您必须定义bean
@Service
public class MapUnitsService {
@Autowired
private List<UnitMapping> unitMappings;
...
@服务
公共类MapUnitsService{
@自动连线
私有列表映射;
...
既然类型信息在运行时消失了,spring如何知道向unitMappings注入什么呢?基本上,spring将在该类型的应用程序上下文中注入所有bean。您必须定义bean:
@Bean
List<UnitMapping> unitMappings(){
return new UnitMapping();
}
@Bean
列表unitMappings(){
返回新的UnitMapping();
}
Spring 4将自动注入泛型作为@限定符的形式,如下:
@Autowired
private List<UnitMapping> unitMappings;
@Autowired
私有列表映射;
提供负责泛型注入的类是
这比预期的要容易,因为反射提供了所需的信息:
public class Main {
List<String> test = new ArrayList<>();
public static void main(String[] args) throws IOException, NoSuchFieldException {
Field field = Main.class.getDeclaredField("test");
System.out.println(field.getGenericType().getTypeName());
}
}
公共类主{
列表测试=新建ArrayList();
公共静态void main(字符串[]args)引发IOException、NoSuchFieldException{
Field=Main.class.getDeclaredField(“测试”);
System.out.println(field.getGenericType().getTypeName());
}
}
是的,我知道,但是Spring如何在运行时知道列表是一个列表呢?我还以为类型被删除了呢?