首先创建一个接口和两个实现类:
public interface BeanInterface {
}
@Component
public class BeanImplOne implements BeanInterface {
}
@Component
public class BeanImplTwo implements BeanInterface {
}
下面将这两个实现类实例注入到集合中:
@Component
public class BeanInvoke {
@Autowired
private List<BeanInterface> beanInterfaceList;
@Autowired
private Map<String, BeanInterface> beanInterfaceMap;
@Autowired
private Set<BeanInterface> beanInterfaceSet;
public void say() {
System.out.println("list...");
if (null != beanInterfaceList && 0 != beanInterfaceList.size()) {
for (BeanInterface bean : beanInterfaceList) {
System.out.println(bean.getClass().getName());
}
}
System.out.println("map...");
if (null != beanInterfaceMap && 0 != beanInterfaceMap.size()) {
for (Map.Entry<String, BeanInterface> m : beanInterfaceMap.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue().getClass().getName());
}
}
System.out.println("set...");
if (null != beanInterfaceSet && 0 != beanInterfaceSet.size()) {
for (BeanInterface bean : beanInterfaceSet) {
System.out.println(bean.getClass().getName());
}
}
}
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDemoApplicationTests {
@Autowired
BeanInvoke beanInvoke;
@Test
public void test1(){
beanInvoke.say();
}
}
结果:
list...
com.demo.spring.BeanImplOne
com.demo.spring.BeanImplTwo
map...
beanImplOne com.demo.spring.BeanImplOne
beanImplTwo com.demo.spring.BeanImplTwo
set...
com.demo.spring.BeanImplOne
com.demo.spring.BeanImplTwo
看到已经将两个实例注入到集合中了。
版权声明:本文为const_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。