Bean的作用域
您不仅可以控制要插入到从特定bean定义创建的对象中的各种依赖项和配置值,还可以控制从特定bean定义创建的对象的范围。这种方法功能强大且灵活,因为您可以选择通过配置创建的对象的范围,而不必在Java类级别上烘烤对象的范围。可以将Bean定义为部署在多个范围之一中。Spring框架支持六个范围,其中只有在使用网络感知的情况下才能使用其中四个ApplicationContext
。您还可以创建 自定义范围。
Scope | Description |
---|---|
singleton | (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext . |
session | Scopes a single bean definition to the lifecycle of an HTTP Session . Only valid in the context of a web-aware Spring ApplicationContext . |
application | Scopes a single bean definition to the lifecycle of a ServletContext . Only valid in the context of a web-aware Spring ApplicationContext . |
websocket | Scopes a single bean definition to the lifecycle of a WebSocket . Only valid in the context of a web-aware Spring ApplicationContext . |
范围 | 描述 |
---|---|
单例 | (默认值)将每个Spring IoC容器的单个bean定义范围限定为单个对象实例。 |
原型 | 将单个bean定义的作用域限定为任意数量的对象实例。 |
request | 将单个bean定义的范围限定为单个HTTP请求的生命周期。也就是说,每个HTTP请求都有一个在单个bean定义的后面创建的bean实例。仅在可感知网络的Spring上下文中有效ApplicationContext 。 |
session | 将单个bean定义的范围限定为HTTP的生命周期Session 。仅在可感知网络的Spring上下文中有效ApplicationContext 。 |
application | 将单个bean定义的作用域限定为的生命周期ServletContext 。仅在可感知网络的Spring上下文中有效ApplicationContext 。 |
websocket | 将单个bean定义的作用域限定为的生命周期WebSocket 。仅在可感知网络的Spring上下文中有效ApplicationContext 。 |
单例模式 spring默认机制
<bean id="address" class="com.liu.pojo.Address" scope="singleton">
<property name="address" value="沈阳"></property>
</bean>
通过容器创建的所有对象,都是同一个对象(内存完全相同)
public class SpringTest {
@Test
public void Test() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
/* Student student = (Student)context.getBean("student");
System.out.println(student.toString());*/
Address address = (Address) context.getBean("address");
Address address1 = (Address) context.getBean("address");
if(address==address1) {
System.out.println(true);
}
}
}
//true
原型模式 创建的所有对象都不一样 ( 每次getBean都会产生新对象)
<bean id="address" class="com.liu.pojo.Address" scope="prototype">
<property name="address" value="沈阳"></property>
</bean>
//测试代码返回 false
request、session、application、websocket
只能在web中使用