1. 程式人生 > >Spring學習歷程---request,session與globalSession作用域

Spring學習歷程---request,session與globalSession作用域

與web容器有關的作用域,首先要在Web容器裡進行一些配置。

<web-app>
    ...
    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>
    ...
</web-app>

Request作用域

考慮下面bean定義:

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>

針對每次HTTP請求,Spring容器會根據loginAction bean定義建立一個全新的LoginAction bean例項, 且該loginAction bean例項僅在當前HTTP request內有效,因此可以根據需要放心的更改所建例項的內部狀態, 而其他請求中根據loginAction bean定義建立的例項,將不會看到這些特定於某個請求的狀態變化。 當處理請求結束,request作用域的bean例項將被銷燬。

Session作用域

考慮下面bean定義:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>

針對某個HTTP Session,Spring容器會根據userPreferences bean定義建立一個全新的userPreferences bean例項, 且該userPreferences bean僅在當前HTTP Session內有效。 與request作用域一樣,你可以根據需要放心的更改所建立例項的內部狀態,而別的HTTP Session中根據userPreferences建立的例項, 將不會看到這些特定於某個HTTP Session的狀態變化。 當HTTP Session最終被廢棄的時候,在該HTTP Session作用域內的bean也會被廢棄掉。

global session作用域


考慮下面bean定義:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="globalSession"/>
global session作用域類似於標準的HTTP Session作用域,不過它僅僅在基於portlet的web應用中才有意義。Portlet規範定義了全域性Session的概念,它被所有構成某個portlet web應用的各種不同的portlet所共享。在global session作用域中定義的bean被限定於全域性portlet Session的生命週期範圍內。

請注意,假如你在編寫一個標準的基於Servlet的web應用,並且定義了一個或多個具有global session作用域的bean,系統會使用標準的HTTP Session作用域,並且不會引起任何錯誤。

作用域依賴問題

If you want to inject (for example) an HTTP request scoped bean into another bean of a longer-lived scope, you may choose to inject an AOP proxy in place of the scoped bean. That is, you need to inject a proxy object that exposes the same public interface as the scoped object but that can also retrieve the real target object from the relevant scope (such as an HTTP request) and delegate method calls onto the real object.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- an HTTP Session-scoped bean exposed as a proxy -->
    <bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
        <!-- instructs the container to proxy the surrounding bean -->
        <aop:scoped-proxy/>
    </bean>

    <!-- a singleton-scoped bean injected with a proxy to the above bean -->
    <bean id="userService" class="com.foo.SimpleUserService">
        <!-- a reference to the proxied userPreferences bean -->
        <property name="userPreferences" ref="userPreferences"/>
    </bean>
</beans>