1.lazy-init
有两个属性值分别为 true,false。
当true时,就会进行懒加载。在容器初始化的过程中不会进行依赖注入,只有当第一个getBean()执行时才会实例化bean。
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");//new ClassPathXmlApplicationContext("application.xml") 创建IoC容器,并按照application.xml配置的信息创建对象
// Object obj1=
applicationContext.getBean("userinfo");
// System.out.println(obj1);
// applicationContext.close();
}
}
比如上图代码中,不会实例化bean。但去掉注释掉段落的注释,就会实例化对象。
2.scope
scope用于生命bean在spring IOC中的存活时间。
有五种属性:singleton,propertype,request,session,globe
singleton:单例模式,每个spring IOC中只有一个实例对象。
propertype:默认模式,每个spring IOC中有多个实例对象。
3.Spring对象生命周期
先创建一个类User
public class User {
static {
System.out.println("静态代码块");
}
static {
System.out.println("非静态代码块");
}
public User(){
System.out.println("构造方法");
}
private String name;
public String getName() {
System.out.println("get方法");
return name;
}
public void setName(String name) {
System.out.println("set方法");
this.name = name;
}
public void init() {
System.out.println("init方法");
}
public void destroy() {
System.out.println("destroy方法");
}
}
再利用Spring创建对象,如第一段代码所示。
观察控制台,输出顺序为
- 静态代码块
- 非静态代码块
- 构造方法
- set方法
- init方法
- com.jd.vo.User@f5e5e3
- destroy方法
需要注意,如果想要执行getset方法,scope中必须为singleton。
destory方法在applicationContext.close();后执行