<bean id="loginAction" class="org.han.action.LoginAction" scope="singleton">
<property name="user" ref="user"></property>
</bean>
在spring2.0以前bean只有2种做用域即:singleton(单例)、non-singleton(也称prototype), Spring2.0之后,增长了session、request、global session三种专用于Web应用程序上下文的Bean。所以,默认状况下Spring2.0如今有五种类型的Bean。固然,Spring2.0对Bean的类型的设计进行了重构,并设计出灵活的Bean类型支持,理论上能够有无数多种类型的Bean,用户能够根据本身的须要,增长新的Bean类型,知足实际应用需求。java
一、singleton和prototype做用域web
<bean id="date" class="java.util.Date" scope="singleton"></bean>
ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); Date d=context.getBean("date",Date.class); System.out.println(d); Thread.sleep(5000); d=context.getBean("date",Date.class); System.out.println(d);
上述示例中获得的时间将是同样的
修改一下:spring
<bean id="date" class="java.util.Date" scope="prototype"></bean>
当使用prorotype做为做用域时,Bean会致使每次对该Bean的请求都建立一个Bean实例,因此对有状态的Bean应该使用prorotype做用域,无状态Bean则使用singleton做用域。还有就是Spring不能对一个prototype做用域 bean的整个生命周期负责,容器在初始化、配置、装饰或者是装配完一个prototype实例后,将它交给客户端,随后就对该prototype实例漠不关心了。无论何种做用域,容器都会调用全部对象的初始化生命周期回调方法,而对prototype而言,任何配置好的析构生命周期回调方法都将不会被调用。清除prototype做用域的对象并释听任何prototype bean所持有的昂贵资源,都是客户端代码的职责。(让Spring容器释放被singleton做用域bean占用资源的一种可行方式是,经过使用bean的后置处理器,该处理器持有要被清除的bean的引用。)设计模式
<web-app> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> </web-app>
若是是Servlet2.4之前的web容器,那么你要使用一个javax.servlet.Filter的实现:缓存
<filter> <filter-name>requestContextFilter</filter-name> <filter-class> org.springframework.web.filter.RequestContextFilter </filter-class> </filter> <filter-mapping> <filter-name>requestContextFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.一、request
request表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效。session
<bean id="loginAction" class="org.han.action.LoginAction" scope="request"/>
<bean id="loginAction" class="org.han.action.LoginAction" scope="session"/>
<bean id="loginAction" class="org.han.action.LoginAction" scope="globalSession"/></span>
在spring2.0中做用域是能够任意扩展的,可是不能覆盖singleton和prototype,spring的做用域由接口org.springframework.beans.factory.config.Scope来定义,自定义本身的做用域只要实现该接口便可app