方式一:使用Map<String,T>
Spring在处理该依赖项时,存入的Key为beanName,Value为Bean实例。
代码示例:
public class MainTest {
@Autowired
private Map<String, CustomizedService> customizedServiceMap;
public static void main(String[] args) {
//
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(CustomizedServiceImpl.class,CustomizedServiceImpl2.class,MainTest.class);
context.refresh();
System.out.println(context.getBean(MainTest.class).customizedServiceMap);
}
}
运行结果:
方式二:使用Collection
代码示例
public class MainTest {
@Autowired private Map<String, CustomizedService> customizedServiceMap;
@Autowired private Collection<CustomizedService> customizedServiceList;
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(CustomizedServiceImpl.class, CustomizedServiceImpl2.class, MainTest.class);
context.refresh();
// System.out.println(context.getBean(MainTest.class).customizedServiceMap);
System.out.println(context.getBean(MainTest.class).customizedServiceList);
}
}
运行结果:
方式三:T[]
代码示例:
public class MainTest {
@Autowired private Map<String, CustomizedService> customizedServiceMap;
@Autowired private Collection<CustomizedService> customizedServiceList;
@Autowired private CustomizedService[] customizedServices;
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(CustomizedServiceImpl.class, CustomizedServiceImpl2.class, MainTest.class);
context.refresh();
// System.out.println(context.getBean(MainTest.class).customizedServiceMap);
System.out.println(Arrays.toString(context.getBean(MainTest.class).customizedServices));
// System.out.println(context.getBean(MainTest.class).customizedServiceList);
}
}
运行结果: