bean 的作用域

 

bean 的作用域

 

singleton:在每个Spring IoC容器中一个bean定义对应一个对象实例。

prototype: 一个bean定义对应多个对象实例。

request:在一次HTTP请求中,一个bean定义对应一个实例;即每次HTTP请求将会有各自的bean实例, 它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。

session:在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。

global session:在一个全局的HTTP Session中,一个bean定义对应一个实例。典型情况下,仅在使用portlet context的时候有效。该作用域仅在基于web的Spring ApplicationContext情形下有效。

 

在 Spring 中,可以在 <bean> 元素的 scope 属性里设置 Bean 的作用域。

默认情况下,Spring 只为每个在 IOC 容器里声明的 Bean 创建唯一一个实例,整个 IOC 容器范围内都能共享该实例:所有后续的 getBean() 调用和 Bean 引用都将返回这个唯一的 Bean 实例。该作用域被称为 singleton,它是所有 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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!--bean的作用域-->
	<!--
	        使用bean的scope来配置bean的作用域
	      1) singleton:默认值。容器初始化时创建bean实例。在整个容器的生命周期内只创建这个一个bean,单例的。
	      2) prototype:原型的。容器初始化时不创建bean实例。而在每次请求时都创建一个新的bean实例,并返回。
	-->

	<!--配置一个 bean-->
	<!--bean默认为单例-->
	<bean id="appRequest1" class="xyz.huning.spring4.di.xml.beancfg.scope.AppRequest">
		<property name="id" value="1"></property>
		<property name="status" value="send"></property>
	</bean>
	
	<!-- 配置一个单例 bean -->
	<bean id="appResponse1" class="xyz.huning.spring4.di.xml.beancfg.scope.AppResponse" scope="singleton">
		<property name="id" value="2"></property>
		<property name="status" value="waiting"></property>
	</bean>
	
	<!--配置一个 原型bean-->
	<bean id="appSession1" class="xyz.huning.spring4.di.xml.beancfg.scope.AppSession" scope="prototype">
		<property name="id" value="3"></property>
		<property name="status" value="running"></property>
	</bean>
	
</beans>

 

 

 

猜你喜欢

转载自ihuning.iteye.com/blog/2224177