Autowired注解
以往我认知里@Autowire可以注入单个Bean, 但实际上它可将所有继承了相同接口的Bean注入为List. 此外它还可以自动导入{beanName, interface}形式的Map. 话不多说, 直接上代码:
使用后自动导入依赖, 它可注解在接口对应的List上或者value为对象的Map上 ,直接上代码:
public interface BeanInterface {
public void say();
}
@Component
@Order(1)
public class BeanImplOne implements BeanInterface {
@Override
public void say() {
System.out.println("aaa");
}
}
@Component
@Order(2)
public class BeanImplTwo implements BeanInterface {
@Override
public void say() {
System.out.println("bbb");
}
}
编写测试类:
@Component
public class BeanInvoke {
@Autowired
List<BeanInterface> list;
@Autowired
Map<String, BeanInterface> map;
@Bean
public void test() {
for (BeanInterface beanInterface : list) {
beanInterface.say();
}
for (String s : map.keySet()) {
System.out.println(s + "-->" + map.get(s));
}
}
}
------------------------------------
aaa
bbb
beanImplOne-->com.wang.multiBean.BeanImplOne@74ecacc3
beanImplTwo-->com.wang.multiBean.BeanImplTwo@517a2b0
- Order: 继承了相同接口的实现类对应的Bean被注入的顺序
- Map的String为Bean的名字
标签:Map,Autowire,void,List,say,Bean,public From: https://www.cnblogs.com/shmilyt/p/17054565.html