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

前端 未结 1 1423
囚心锁ツ
囚心锁ツ 2021-02-10 18:46

I am pretty new in Spring MVC and I have a doubt about the session scope of a bean.

Into a project I have a Cart bean, this one:

         


        
相关标签:
1条回答
  • 2021-02-10 18:53

    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:

    • What is the difference between JDK dynamic proxy and CGLib?

    Here's a related post about the request scope:

    • Inject HttpServletRequest into Controller
    0 讨论(0)
提交回复
热议问题