Bean的作用域
Bean的作用域是指Bean实例的有效范围。
作用域名称 | 描述 |
---|---|
single | 单例模式。在单例模式下,Spring容器中只会存在一个共享的Bean实例,所有对Bean的请求,只要请求的id(或name)与Bean的定义相匹配,就会返回Bean的同一个实例。 |
prototype | 原型模式。每次从容器中请求Bean时,都会产生一个新的实例 |
request | 每一个HTTP请求都会有自己的Bean实例,该作用域只能在基于Web的Spring ApplicationContext中使用 |
session | 每一个HttpSession请求都会有自己的Bean实例,该作用域只能基于Web的Spring ApplicationContext中使用。 |
global session | 限定一个Bean的作用域为Web应用(HttpSession)的生命周期,只有在Web应用中使用Spring时,该作用域才有效 |
其中single【默认】和prototype是两种最为常用的作用域。
singleton作用域
singleton是Spring容器默认的作用域,当Bean的作用域为singleton时,Spring容器只为Bean创建一个实例,该实例可以重复使用。避免反复创建和销毁实例造成的资源消耗。
public class Bean1 {
public Bean1(){
System.out.println("这是Bean1");
}
}
<bean id="bean1" class="com.hua.dao.Bean1" scope="singleton"/>
public class MyTest3 {
@Test
public void ScopeTest(){
ApplicationContext ac=new ClassPathXmlApplicationContext("bean1.xml");
Bean1 bean1 = ac.getBean("bean1", Bean1.class);
Bean1 bean11 = ac.getBean("bean1", Bean1.class);
System.out.println(bean1==bean11);
}
}
由此表明,对singleton作用域的Bean,程序每次请求Bean都会返回同一个实例。
prototype作用域
当Bean的作用域为prototype时,每次对Bean请求时都会**创建一个新的Bean实例,**Spring容器只负责创建实例而不再管理其生命周期。
由此表明Spring容器获取Bean1类的两个实例不是同一个实例。对于prototype作用域的Bean,程序每次请求Bean都会返回一个新的实例。