当配置类中只有一个该类型Bean时,在注入的时候。其名字随意。例如:
@Configuration
public class ComputerConfig {
@Bean
public Computer computer() {
Computer computer = new Computer();
computer.setId(1);
computer.setType("笔记本");
computer.setName("戴尔笔记本");
return computer;
}
}
注入时:
@Resource
private Computer dell;
当配置类中有多个该类型的Bean时,名字不能相同,并且注入时也要按照Bean的名称来注入。例如:
@Configuration
public class ComputerConfig {
@Bean
public Computer dell() {
Computer computer = new Computer();
computer.setId(1);
computer.setType("笔记本");
computer.setName("戴尔笔记本");
return computer;
}
@Bean
public Computer apple() {
Computer computer = new Computer();
computer.setId(2);
computer.setType("笔记本");
computer.setName("苹果笔记本");
return computer;
}
@Bean("hp")
public Computer huipu() {
Computer computer = new Computer();
computer.setId(3);
computer.setType("笔记本");
computer.setName("惠普笔记本");
return computer;
}
}
注入:
@Resource
private Computer dell;
@Resource
private Computer apple;
@Resource
private Computer hp;