7.5.4 Session scope

Consider the following XML configuration for a bean definition:

考虑以下关于bean定义的XML配置:

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

The Spring container creates a new instance of the UserPreferences bean by using the userPreferences bean definition for the lifetime of a single HTTP Session. In other words, the userPreferences bean is effectively scoped at the HTTP Session level. As with request-scoped beans, you can change the internal state of the instance that is created as much as you want, knowing that other HTTP Session instances that are also using instances created from the same userPreferencesbean definition do not see these changes in state, because they are particular to an individual HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session is also discarded.

Spring容器通过在userPreferences单个HTTP Session的生存期内使用bean定义来创建UserPreferences bean的新实例。换句话说,userPreferences bean在HTTP Session级别上有效地作用域。与request-scopedbean一样,您可以根据需要更改创建的实例的内部状态,因为知道Session同样使用从同一userPreferencesbean定义创建的实例的其他HTTP 实例在状态中看不到这些更改,因为它们是特定的个人HTTP Session。当HTTP Session最终被丢弃时,也将丢弃作用于该特定HTTP Session的bean 。

When using annotation-driven components or Java Config, the @SessionScope annotation can be used to assign a component to the session scope.

使用注解驱动的组件或Java Config时,@SessionScope注解可用于将组件分配给session范围。

@SessionScope
@Component
public class UserPreferences {
    // ...
}

猜你喜欢

转载自blog.csdn.net/weixin_41648566/article/details/81387629