singleton:html
單例模式,針對每一個spring容器,只有一個該類的實例被管理,每次調用此實例都是同一個對象被返回,因此適用於無狀態bean。默認狀況下,singleton做爲spring容器中bean的做用域。web
<bean id="accountService" class="com.foo.DefaultAccountService"/> <!-- the following is equivalent, though redundant (singleton scope is the default); using spring-beans-2.0.dtd --> <bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/> <!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd --> <bean id="accountService" class="com.foo.DefaultAccountService" singleton="true"/>
prototype:spring
針對每一次bean調用,注入或者程序中顯式調用getBean(...)相似方法,都有一個新的對象被初始化後返回,因此適用於有狀態bean。值得注意的是儘管初始化回調方法依然會被調用,可是聲明爲prototype的bean的「銷燬」回調方法不會被容器調用。spring container初始裝配以後將控制權交給客戶代碼,客戶代碼須要承擔釋放資源的責任。(spring 提供prototype資源的釋放方案,BeanPostProcessors
)。session
<!-- using spring-beans-2.0.dtd --> <bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/> <!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd --> <bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/>
request,session,global session:mvc
以上三種顧名思義,做用域分別是http request級別,session級別。spring context須要是web實現(好比:XmlWebApplicationContext)。DispatcherServlet/DispatcherPortlet,RequestContextListener
或RequestContextFilter
負責將每一個http request/session 綁定到負責相應這個請求的線程上,並使得聲名爲request/session做用域的bean在後續調用中可用。app
spring mvcui
<servlet> <servlet-name>rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet>
servlet 2.4+url
<web-app> ... <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> ... </web-app>
servlet 2.3spa
<web-app> .. <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> ... </web-app>
refer to spring referenceprototype