Bean的作用域
Bean的作用域对Bean的生命周期和创建方式产生影响。Spring Framework支持五种作用域。
![Bean作用域类型](https://img-blog.csdn.net/20150802214922793)
Singleton作用域
当把一个bean定义设置为singlton作用域时,Spring IoC容器只会创建该bean定义的唯一实例。这个单一实例会被存储到单例缓存(singleton cache)中,并且所有针对该bean的后续请求和引用都将返回被缓存的对象实例。bean作用域默认为Singleton。
<!--验证-->
<bean id="personService" class="com.test.PersonServiceBean" ></bean>
public class SpringTest01 {
@Test
public void instanceSpring (){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml" );
PersonService personService1 = (PersonService)ctx.getBean("personService" );
PersonService personService2 = (PersonService)ctx.getBean("personService" );
System.out .println(personService1==personService2);
}
}
Prototype作用域
Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例 。
根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。
<bean id="personService" class ="com.test.PersonServiceBean" scope ="prototype" ></bean>
Bean的生命周期
初始化
当scope=singleton,即默认情况,会在容器初始化时实例化。但我们可以指定Bean节点的lazy-init=”true”来延迟初始化bean,这时候,只有第一次获取bean才会初始化bean,即第一次请求该bean时才初始化。
<bean id=”xxx” class =”examples.test.OrderServiceBean” lazy -init=”true ” />
<beans default -lazy -init=”true ” …>
生命周期
构造器、init方法、获取bean后的操作、destroy方法(ctx.close时执行).
public class PersonServiceBean implements PersonService {
public void init (){
System.out.println("Get the database connection and initialize other beans!" );
}
public PersonServiceBean (){
System.out.println("PersonServiceBean is initialized!" );
}
public void destroy (){
System.out.println("close the database connection!" );
}
}
注意:如果bean的scope设为prototype时,当ctx.close时,destroy方法不会被调用.
对于prototype作用域的bean,有一点非常重要,那就是Spring不能对一个prototype bean的整个生命周期负责:容器在初始化、配置、装饰或者是装配完一个prototype实例后,将它交给客户端,随后就对该prototype实例不闻不问了。不管何种作用域,容器都会调用所有对象的初始化生命周期回调方法。但对prototype而言,任何配置好的析构生命周期回调方法都将不会 被调用
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" init-method="init" destroy-method="destroy" />
public class SpringTest {
@Test
public void instanceSpring (){
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml" );
System.out .println("------------------" );
PersonService personService = (PersonServiceBean)ctx.getBean("personService" );
ctx.close();
}
}
按上述配置后,初始化时会调用 init()方法,ctx.close()时会调用destroy()方法。