当通过Spring容器创建一个Bean实例时,不仅可以完成Bean实例的实例化,还可以包含了指定的作用域。Spring支持以下5种作用域。
1) singleton:单例模式,在整个SpringIoC容器中,singleton作用域的Bean将只生成一个实例。
2) prototype:每次通过容器的getBean()方法获取prototype作用的Bean时,都将产生一个实例。
3) request:对于一次HTTP请求,request作用域的Bean将生成一个实例,这意味着,在同一次HTTP请求内,程序每次请求该Bean,得到的总是同一个实例。只有在WEB应用中使用Spring时,该作用域才会真正有效。
4) session:对于一次HTTP会话,session作用域的Bean将会生成一个实例,这意味着,在同一次HTTP会话内,程序每次请求该Bean,得到的总是同一个实例。只有在web应用中使用Spring时,该作用域才真正有效。
5) global session:每个全局HTTPSession对应一个Bean实例。在典型的情况下,仅在使用portlet context的时候有效。只有在Web应用中使用Spring时,该作用域才真正有效。
下面配置singleton Bean和prototypeBean各一个。
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 配置一个singleton Bean实例 -->
<bean id="p1" class="com.owen.app.service.Person"/>
<!-- 配置一个prototype Bean实例 -->
<bean id="p2" class="com.owen.app.service.Person"
scope="prototype"/>
<bean id="date" class="java.util.Date"/>
</beans>
下面配置一个request Bean不过要在web.xml文件中添加:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
之后在applicationContext.xml文件中配置。
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 指定使用request作用域 -->
<bean id="p" class="com.owen.app.service.Person"
scope="request"/>
</beans>