======================
Spring IoC对象实例模式
======================
定义类:
public class Book {
private int id;
private String title;
public Book(int id, String title) {
System.out.println("Book类的构造器");
this.id = id;
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
'}';
}
}
创建对象:
测试:
public class SpringTest {
public static void main(String[] args) {
...
// 对象作用域
System.out.println("获取ba对象");
Book ba = context.getBean("book", Book.class);
System.out.println(Integer.toHexString(System.identityHashCode(ba)));
...
}
}
Book类的构造器 \ 默认情况下,Spring容器
获取ba对象 / 在初始化过程中创建对象
441772e
bean标签的lazy-init属性取true,表示随用随创建:
获取ba对象 \ 随用随建
Book类的构造器 / 不用不建
441772e
再增加一个对象:
public class SpringTest {
public static void main(String[] args) {
...
// 对象作用域
System.out.println("获取ba对象");
Book ba = context.getBean("book", Book.class);
System.out.println(Integer.toHexString(System.identityHashCode(ba)));
System.out.println("获取bb对象");
Book bb = context.getBean("book", Book.class);
System.out.println(Integer.toHexString(System.identityHashCode(bb)));
...
}
}
获取ba对象
Book类的构造器
441772e \
获取bb对象 内存地址相同,ba和bb是同一个对象——单例模式
441772e /
bean标签的scope属性取prototype,表示多例模式:
获取ba对象
Book类的构造器
441772e \
获取bb对象 内存地址不同
Book类的构造器 两个独立对象
7334aada /
在多例模式下,容器中的对象总是随用随创建,lazy-init属性不起作用。
例程:SpringIoC
-----------------------------------------------------
| scope
bean |----------------------------
| singleton(默认) | prototype
-----------------------------------------------------
| false(默认) | 饿汉单例 |
layzy-init|-------------------------------| 多例
| true | 懒汉单例 |
-----------------------------------------------------