Member-only story
In Spring Framework, a bean’s scope determines the lifecycle and visibility of that bean in the contexts it is being used. There are five types of bean scopes supported :
- Singleton (default): This is the default scope for a Spring Bean. Only one instance of the bean will be created for each Spring IoC container. A real-world example could be a service class, like UserService or ProductService, where you may only need a single instance of the bean.
- Prototype: A new instance will be created every time the bean is requested. This is useful when you want a bean to hold state that is specific to the client. For example, if you have a bean that holds a shopping cart, that bean needs to be prototype scoped because every user will need to have their own shopping cart.
- Request: A new bean will be created for each HTTP request. This is only valid in the context of a web-aware Spring ApplicationContext. This could be useful for a bean that carries information specific to an HTTP request, such as a UserContext bean that holds user information.
- Session: A new bean will be created for each HTTP session by the container. This is also only valid in the context of a web-aware Spring ApplicationContext. A common use case would be user authentication. Once a user is authenticated, the same user data needs to be available for that entire session.
- Global Session: This is a bean scope that is scoped at the global HTTP session level. It is typically only used when creating…