在 Spring 中, 可以在
<bean>
元素的 scope 屬性裡設定 Bean 的作用域.
bean的五種作用域
singleton作用域
預設情況下, Spring 隻為每個在 IOC 容器裡聲明的 Bean 建立唯一一個執行個體, 整個 IOC 容器範圍内都能共享該執行個體:所有後續的 getBean() 調用和 Bean 引用都将傳回這個唯一的 Bean 執行個體.該作用域被稱為 singleton, 它是所有 Bean 的預設作用域。下面使用代碼執行個體講解:
- Car類
package com.spring.ioc;
public class Car {
private String brand;
private double price;
public Car() {
System.out.println("建立Car執行個體...");
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
}
注意Car類的構造函數
public Car() {
System.out.println("建立Car執行個體...");
}
配置bean:
<bean id="car" class="com.spring.ioc.Car" scope="singleton">
<property name="brand" value="BMW"></property>
<property name="price" value="1000"></property>
</bean>
測試1:
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");
運作結果:
預設情況下,bean的scope是singleton,該執行個體在bean容器加載時就開始建立
看下面測試:
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");
Car car1 = (Car) ctx.getBean("car");
Car car2 = (Car) ctx.getBean("car");
System.out.println(car1 == car2);
car這個bean是單例的,這也是singleton的作用,聲明該bean單例
prototype作用域
将bean的scope設定為 prototype
<bean id="car" class="com.spring.ioc.Car" scope="prototype">
<property name="brand" value="BMW"></property>
<property name="price" value="1000"></property>
</bean>
測試1:
//加載bean容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");
測試時隻加載bean容器,發現并沒有建立Car執行個體。
測試2:
//加載bean容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");
Car car1 = (Car) ctx.getBean("car");
Car car2 = (Car) ctx.getBean("car");
System.out.println(car1 == car2);
使用getBean()方法擷取兩個bean執行個體并比較
每擷取一次bean都會建立一個新的bean執行個體
其他幾個由于不經常用這裡就不講了。
本系列參考視訊教程: http://edu.51cto.com/course/1956.html