本篇文章讲bean的作用域
在默认情况下,IOC容器创建的对象是单例的,即多次使用getBean方法时会返回同一个bean对象,即bean对象只会被创建一次。
用一个简单的例子可以证明这一点。
在Address类的构造函数中打印一句话:
package beans;
public class Address {
private String city;
private String street;
public Address() {
super();
System.out.println("address construct..");
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
@Override
public String toString() {
return "Address [city=" + city + ", street=" + street + "]";
}
}
在spring bean配置文件中缺省的使作用域为单例模式:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="beans.Address">
<property name="city" value="GuangZhou"></property>
<property name="street" value="Shangxiajiu"></property>
</bean>
<bean id="person" class="beans.Person" depends-on="address">
<property name="name" value="Tom"></property>
</bean>
</beans>
使用main函数测试一下:
package beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Address address = ctx.getBean(Address.class);
address = ctx.getBean(Address.class);
}
}
可以在控制台上看到:
address construct..
现在我们使scope=“prototype”看看会输出什么?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="beans.Address" scope="prototype">
<property name="city" value="GuangZhou"></property>
<property name="street" value="Shangxiajiu"></property>
</bean>
<bean id="person" class="beans.Person" depends-on="address">
<property name="name" value="Tom"></property>
</bean>
</beans>
运行main函数会发现输出了3行address construct..,这是因为我们在main函数中使用了两次的getBean方法,然后person bean中依赖了address,因此address被实例化了3次。
总结一下就是,singleton是默认值,在容器初始化时就创建bean的实例,在整个容器的生命周期中只创建单个bean,而prototype在每次请求时都创建一个新的bean实例