Spring容器会在创建容器的时候提前初始化Singleton作用域的bean,但是如果Bean被标注懒加载,则该bean只有在被需要的时候才会被初始化。
通过注解注入Bean
1、通过方法注入Bean
(1)通过构造方法注入Bean
(2)通过set方法注入Bean
2、通过属性注入Bean
假设注入的Bean为AnotherBean
@Component
public class MyBean{
private AnotherBean anotherbean1;
@Autowired
public MyBean(AnotherBean anotherbean1){
this.anotherbean1 = anotherbean1;
}
private AnotherBean anotherbean2;
@Autowired
public void setAnotherbean2(AnotherBean anotherbean2){
this.anotherbean2 = anotherbean2;
}
@Autowired
private AnotherBean anotherbean3;
//对于集合
private List<String> stringList;
//get/set方法
public List<String> getStringList(){
return stringList;
}
@Autowired
public void setStringList(List<string> stringList){
this.stringList = stringList;
}
public String toString(){
//方法重写
}
}
建立Spring的configuration类
@Configuration
@ComponentScan("要扫描的包路径")
public class MyConfiguration{
@Bean //告诉spring,这是将要交由spring管理的bean
public List<String> stringList(){
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
return list;
}
}