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 userPreferences
bean 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-scoped
bean一样,您可以根据需要更改创建的实例的内部状态,因为知道Session
同样使用从同一userPreferences
bean定义创建的实例的其他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 {
// ...
}