Spring Beans and Bean Scopes Explanation

In Spring Framework, a bean is an object that is managed by the Spring container. A bean is an instance of a class that is configured and managed by Spring, allowing for easier dependency management and object creation.

In Spring, the beans are defined in XML or Java configuration files, and the Spring container is responsible for instantiating, configuring, and managing these beans.

Bean Scopes: In Spring, a bean scope defines the lifecycle and visibility of a bean instance. The Spring framework provides several bean scopes to control the lifecycle of a bean instance. The bean scope is specified by the scope attribute in the bean configuration.

  1. Singleton: This is the default scope in Spring. A single bean instance is created and used throughout the application. Every time the bean is injected, the same instance is returned.
<bean id="myBean" class="com.example.MyBean" scope="singleton"/>
  1. Prototype: A new instance of the bean is created every time it is requested. This means that every time the bean is injected, a new instance is returned.
<bean id="myBean" class="com.example.MyBean" scope="prototype"/>
  1. Request: A bean instance is created once per HTTP request. This scope is only applicable in a web application context.
<bean id="myBean" class="com.example.MyBean" scope="request"/>
  1. Session: A bean instance is created once per user session. This scope is only applicable in a web application context.
<bean id="myBean" class="com.example.MyBean" scope="session"/>
  1. Global Session: A bean instance is created once per global HTTP session. This scope is only applicable in a web application context using Portlet.
<bean id="myBean" class="com.example.MyBean" scope="globalSession"/>

Bean scopes are used to control the lifecycle of a bean instance. Choosing the appropriate scope for a bean is important to ensure that the bean instance behaves as expected in different usage scenarios. For example, a singleton bean might be used for a configuration object that should be used across the application, while a prototype bean might be used for a stateful object that needs to be recreated every time it is used.