【spring框架】bean的生命范围(scope)

来源:互联网 发布:淘宝即将上架抢购攻略 编辑:程序博客网 时间:2024/05/17 19:18
<bean ...></bean>中有一个属性,叫scope,就是设定生命范围的。
其中有这么几个属性:
表 3.4. Bean作用域

作用域 描述 
singleton 
 在每个Spring IoC容器中一个bean定义对应一个对象实例。
 不论你拿多少个bean,都只是一个对象,叫"单例"
 
prototype 
 一个bean定义对应多个对象实例。
 prototype叫"原型",就是谁要原型,我给它一个新的,每一次生成一个新的对象。
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情形下有效。
 
最常用的是singleton和prototype ,默认是singleton。


测试singleton:
beans.xml配置:
<?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-2.5.xsd">  <bean id="u" class="cn.edu.hpu.dao.Impl.UserDaoImpl">  <property name="daoId" value="8"></property>  <property name="daoStatus" value="good"></property>  </bean>  <bean id="userService" class="cn.edu.hpu.service.UserService" scope="singleton"><!--或默认不写-->   <constructor-arg>   <ref bean="u"/>   </constructor-arg>  </bean>  </beans>

测试:
@Testpublic void testAdd() throws Exception{BeanFactory ctx=new ClassPathXmlApplicationContext("beans.xml");UserService userService=(UserService)ctx.getBean("userService");UserService userService2=(UserService)ctx.getBean("userService");System.out.println(userService==userService2);}
结果打印了:true。说明确实使用的是一个对象


测试prototype:
beans.xml配置:
<?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-2.5.xsd">  <bean id="u" class="cn.edu.hpu.dao.Impl.UserDaoImpl">  <property name="daoId" value="8"></property>  <property name="daoStatus" value="good"></property>  </bean>  <bean id="userService" class="cn.edu.hpu.service.UserService" scope="prototype">   <constructor-arg>   <ref bean="u"/>   </constructor-arg>  </bean></beans>

测试:
@Testpublic void testAdd() throws Exception{BeanFactory ctx=new ClassPathXmlApplicationContext("beans.xml");UserService userService=(UserService)ctx.getBean("userService");UserService userService2=(UserService)ctx.getBean("userService");System.out.println(userService==userService2);}
结果打印了:false。说明使用的不是一个对象


一般开发时选择prototype来使用。

转载请注明出处:http://blog.csdn.net/acmman

0 0