How does the session scope of a bean work in a Spring MVC application?

允我心安 提交于 2019-12-03 21:08:12
Sotirios Delimanolis

So, from what I have understand it means that it is automatically created a single bean for each user session.

The session bean will be created per user, but only when requested. In other words, if, for a given request, you don't actually need that bean, the container will not create it for you. It's, in a sense, "lazy".

The typical use is

@Controller
public class MyController {
    @Autowired
    private MySessionScopeBean myBean;
    // use it in handlers
}

Here, you're injecting a session scoped bean into a singleton scope bean. What Spring will do is inject a proxy bean, that, internally, will be able to generate a real MySessionScopeBean object per user and store it in the HttpSession.

The annotation attribute and value

proxyMode = ScopedProxyMode.TARGET_CLASS

defines how Spring will proxy your bean. In this case, it will proxy by retaining the target class. It will use CGLIB for this purpose. An alternative is INTERFACES where Spring uses JDK proxies. These do not retain the class type of the target bean, only its interfaces.

You can read more about proxies here:

Here's a related post about the request scope:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!