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:
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: