4. Spring Bean Scopes and Bean Lifecycle
What is Scope?
A scope refers to the life cycle of a bean. For example how long does the bean live, how many instances are created for the bean and how the bean is shared in the spring environment etc.
Spring framework supports six type of scopes that are described below:
- singleton
- prototype
- request
- session
- global-session
- application
1. Singleton Scope :
- This is default bean scope and Spring container creates only one instance of the bean.It is cached in memory.
- All requests for the bean will return a shared reference to the same bean.
- If In the bean definition the scope is not given, then by default singleton scope is assumed.
- In a given Spring container a singleton scoped bean will be instantiated only once and the same will be used for its lifetime.Singleton scoped beans are mostly used for stateless beans.
How to define the bean scope
We can define the scope of a bean in two ways.
1. Singleton Scope using XML
In singleton bean scope, we need to assign singleton value to the attribute scope.
<bean id="address" class="com.jwt.bean.Address" scope="singleton">
<constructor-arg name="city" value="Bangalore"/>
</bean>
2. Singleton Scope using @Scope Annotation
We can define the bean with singleton scope by using @Scope annotation.
@Scope("singleton")
public class Address {
}
2. prototype Scope :
- If the scope is set to prototype, spring container creates new instance of bean for each and every request for that bean.
- In spring bean dependency, prototype scoped bean is served by creating new instance of bean for each and every bean dependency.
- prototype scope is used for stateful beans.
3. request Scope :
- In spring, request scoped bean is used in HTTP request life-cycle. For each and every HTTP request, new instance of bean is created and is alive for complete HTTP request life-cycle.
- request scoped bean cannot be used with spring standalone application, it can be used only in web application.
- In one HTTP request, only one instance of request scoped bean is created and in other subsequent request another instance of bean is created per request.
- The life cycle of request scoped bean starts and ends within the life cycle of HTTP request. Within HTTP request, the changes done in request scoped bean does not affect the other HTTP request. Once HTTP request is completed, the instance of request scoped bean is also destroyed.
4. session Scope :
- session scoped bean in spring is used in HTTP Session of web application. For each and every HTTP session, only one instance of bean is created and is alive for complete HTTP session life cycle.
- The life cycle of session scoped bean is within the life cycle of HTTP session life cycle. If HTTP session is discarded, the session scoped bean created within HTTP session is also discarded.
- Similar to request scope, it is applicable only for web aware spring application contexts.
5. globalSession Scope :
- globalSession scoped bean is used in portlet based spring web application. Only one instance of globalSession scoped bean is created for life cycle of global HTTP session.
- Global HTTP session is the HTTP session that is shared among all portlets to make a single portlet web application. globalSession scoped bean instance has the life cycle within global HTTP session life cycle.
6. application Scope :
- application scope has been introduced in Spring 4.0. Only one instance of bean is created for the complete life cycle of ServletContext.
- The instance of application scoped bean is stored as ServletContext attribute. application scoped bean is used in spring web application.
- This scope is similar to singleton scope with one difference that application scope is ServletContext specific and singleton scope is spring ApplicationContext specific.
Bean Life Cycle
- In Spring Framework, beans have a lifecycle that goes through several stages, allowing for initialization, customization, and destruction.
- The init method attribute will get specified when the bean needs to get initialized. Similarly, as the init the destroy-method will get called just before the bean is removed from the container.
- In the Spring Framework, the lifecycle of a bean refers to the process from the instantiation of the bean to its disposal.
- The bean lifecycle can be managed through various approaches, including XML-based configuration, interface-based configuration, and annotation-based configuration.
Steps of Bean Life Cycle
1. Initialization
2. Customization
3. Destruction
1. XML-Based Configuration:
- In XML-based configuration, you define the bean lifecycle methods using XML configuration files.
- The two main lifecycle methods are `init-method` and `destroy-method`. The `init-method` is called after the bean is instantiated, and the `destroy-method` is called before the bean is destroyed.
a. Initialisation Callbacks : Inside the method afterPropertiesSet() implement the interface .
b. Destruction Callbacks : Inside the method destroy() implement the interface .
- If you are using the Spring Framework container for non-web application environment you need to register a shutdown hook with JVM using the method called registerShutdownHook(). So doing that ensures a graceful shutdown along with the call to the relevant destroys methods on singleton beans.
c. Default Initialization and Destroy Methods
- You don’t need the declaration of the methods in it and destroy if there are many beans with initialization and destroy methods having same names.
default-init-method = "init"
default-destroy-method = "destroy">
Here's an example:
-config.xml
<bean id="exampleBean" class="com.example.ExampleBean" init-method="init" destroy-method="destroy">
<!-- Bean properties and dependencies -->
</bean>
Pojo.java
public class ExampleBean {
public void init() {
// Initialization code
}
public void destroy() {
// Destruction code
}
}
2. Interface-Based Configuration:
- Alternatively, you can implement the `InitializingBean` and `DisposableBean` interfaces to manage the lifecycle methods.
- The `afterPropertiesSet()` method corresponds to the `init-method`, and the `destroy()` method corresponds to the `destroy-method`.
Here's an example:
java file
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class ExampleBean implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
// Initialization code
}
@Override
public void destroy() throws Exception {
// Destruction code
}
}
3. Annotation-Based Configuration:
- In annotation-based configuration, you can use `@PostConstruct` and `@PreDestroy` annotations to define the initialization and destruction methods, respectively.
Here's an example:
java file
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class ExampleBean {
@PostConstruct
public void init() {
// Initialization code
}
@PreDestroy
public void destroy() {
// Destruction code
}
}
Note: Ensure that your project has the necessary dependencies to support annotations (`javax.annotation`). PostConstruct & PreDestroy are the part JavaEE (Java 8) for the 8 + version we have to add dependency for annotation.
Choose the approach that best fits your application's requirements and coding style. The annotation-based configuration is often preferred for its conciseness and readability.
Comments
Post a Comment