Spring Bean Lifecycle in Java

Any object’s lifecycle describes its birth, how it develops during life, and how it dies. Similarly, the bean life cycle describes the instantiation of the bean. Further, it considers the actions it takes to live and the timing and method of its demise. We’ll talk about the bean’s life cycle in this post.

Spring Bean Lifecycle in Java

The spring container regulates the life cycle of the bean. First, the spring container starts when the application is executed. After that, dependencies are injected after the container produces an instance of a bean per the request. Finally, when the spring container is closed, the bean is destroyed.

Therefore, we can place that code inside the custom init() method and the destroy() method if we want to run it right after closing the spring container and during the bean instantiation. The life cycle of a bean is depicted in the following sample.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>[Container Started] → [Bean Instantiated] → [Dependencies injected]→ [Custom init() method]→ [custom utility method]→ [Custom destroy() method]</pre>
</div>

Note that the custom method names are an alternative to init() and destroy(). Here, we will utilize the init() method to run all of its code once the spring container initializes and the bean is created and the destruct() way to run all its code when the container is closed.

How to apply the bean’s life cycle

There are three approaches to implementing a bean’s life cycle in spring. Let’s look at an illustration to comprehend these three approaches better. To print a message when the Spring container starts and stops, we’ll write and activate the init() and destroy() methods for our bean (CodeWorld.java) in this example.

So, here are the three methods to put this into practice:

Through XML

While defining a bean, we must register the custom init() and destroy() methods inside the Spring XML configuration file to use them. As a result, the subsequent actions are taken:

We must first create the CodeWorld.java bean and add the init() and destroy() methods to the class.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Java program for creating a bean in the spring framework
package beans;

public class CodeWorld {

	// This method is responsible for automatically executing upon the bean's instantiation
	public void init() throws Exception
	{
		System.out.println(
			"Bean CodeWorld has been "
			+ "instantiated and I'm "
			+ "the init() method");
	}

	
	// when the spring container is closed, the following method executes
	public void destroy() throws Exception
	{
		System.out.println(
			"Container has been closed "
			+ "and I'm the destroy() method");
	}
}</pre>
</div>

We now must register the init() and destroy() methods in the spring.xml configuration file.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre><!DOCTYPE>
			
<beans>
	<bean id="cw" class="beans.CodeWorld"
			init-method="init" destroy-method="destroy"/>
	
</beans></pre>
</div>

To run this bean, we must develop a driver class.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>//to call the bean initialized prior, we will utilize  the following Java program

package test;

import org.springframework
	.context
	.ConfigurableApplicationContext;

import org.springframework
	.context.support
	.ClassPathXmlApplicationContext;

import beans.CodeWorld;

// The driver class
public class ClientObject {

	public static void main(String[] args)
		throws Exception
	{

		// Loading the Spring XML configuration
		// file into the spring container and
		// it will create the instance of
		// the bean as it loads into the container

		ConfigurableApplicationContext configurableAC
			= new ClassPathXmlApplicationContext(
				"resources/spring.xml");

		// It will close the spring container
		// and as a result, invokes the
		// destroy() method
		configurableAC.close();
	}
}</pre>
</div>

By Programmatic Approach

We need implementation of our bean with two interfaces, InitializingBean and DisposableBean, and will need to override the afterPropertiesSet() and destroy() methods. It will give the created bean the ability to invoke a custom init() method on the startup of a spring container and a custom destroys () method on closing the container.

The destroy() function is called right after the container closes, but the afterPropertiesSet() method is called as the container starts, and subsequently, there is an instantiation of the bean.

To call the destruct method, we must first call ConfigurableApplicationContext’s close() method. As a result, subsequent actions are taken. To start, we must implement InitializingBean, DisposableBean, and override the afterPropertiesSet() and destroy() methods of the CodeWorld.java bean.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Java program for creating a bean in the spring framework
package beans;

import org.springframework
	.beans.factory.DisposableBean;

import org.springframework
	.beans.factory.InitializingBean;

// CodeWorld class responsible for interface implementation
public class CodeWorld
	implements InitializingBean,
DisposableBean {

	@Override
	// It is the init() method
	// of our bean, and it gets
	// invoked on bean instantiation
	public void afterPropertiesSet()
throws Exception
	{
		System.out.println(
			"Bean CodeWorld has been "
			+ "instantiated and I'm the "
			+ "init() method");
	}

	@Override
	// This method is invoked
	// just after the container
	// is closed
	public void destroy() throws Exception
	{
		System.out.println(
			"Container has been closed "
			+ "and I'm the destroy() method");
	}
}</pre>
</div>

We need to specify the bean and set up the spring.xml XML file.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre><!DOCTYPE>
			
<beans>
	<bean id="cw" class="beans.CodeWorld"/>
	
</beans></pre>
</div>

To run this bean, we must develop a driver class.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Java program for calling the initialized bean above

package test;

import org.springframework
	.context
	.ConfigurableApplicationContext;

import org.springframework
	.context.support
	.ClassPathXmlApplicationContext;

import beans.CodeWorld;

// the driver class
public class ClientObject {

	public static void main(String[] args)
		throws Exception
	{

		//The Spring XML configuration
 file is loaded into the 
// Spring container, and
 as it does so, an instance of the bean
 is // created. 
		ConfigurableApplicationContext configurableAP
			= new ClassPathXmlApplicationContext(
				"resources/spring.xml");

		// It will close the spring container
		// and as a result, invokes the
		// destroy() method
		configurableAP.close();
	}
}
</pre>
</div>

Using Annotation

We must annotate the init() method with the @PostConstruct annotation and the destroy() method with the @PreDestroy annotation to give the newly created bean the ability to call a custom init() method upon the startup of a spring container and a custom destroy() method upon the container’s closure.

Note that we must call ConfigurableApplicationContext’s close() method before calling the destroy() method. As a result, subsequent actions are taken. In this instance, we must first construct the bean HelloWorld.java and annotate the custom init() and destroy() methods with @PostConstruct and @PreDestroy, respectively.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Java program for bean's creation in the spring framework
package beans;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

// CodeWorld class
public class CodeWorld {

	// Annotate this method to execute it
	// automatically as the bean is
	// instantiated
	@PostConstruct
	public void init() throws Exception
	{
		System.out.println(
			"Bean CodeWorld has been "
			+ "instantiated and I'm the "
			+ "init() method");
	}

	// Annotate this method to execute it
	// when the Spring container is closed
	@PreDestroy
	public void destroy() throws Exception
	{
		System.out.println(
			"Container has been closed "
			+ "and I'm the destroy() method");
	}
}</pre>
</div>

We now need to specify the bean and set up the spring.xml XML file.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre><!DOCTYPE">
			
<beans>

	<!-- activate the @PostConstruct and
@PreDestroy annotation -->

	<bean class="org.springframework
.context.annotation
.CommonAnnotationBeanPostProcessor"/>

	<!-- configure the bean -->
	<bean class="beans.CodeWorld"/>
	
</beans>
</pre>
</div>

To run this bean, we must develop a driver class.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Java program for calling the initialized bean above

package test;

import org.springframework
	.context
	.ConfigurableApplicationContext;

import org.springframework
	.context.support
	.ClassPathXmlApplicationContext;

import beans.CodeWorld;

// the driver class
public class ClientObject {

	public static void main(String[] args)
		throws Exception
	{

		// Loading the Spring XML configuration
		// file into Spring container and
		// it will create the instance of the
		// bean as it loads into the container
		ConfigurableApplicationContext configurableAP
			= new ClassPathXmlApplicationContext(
				"resources/spring.xml");

		// It will close the Spring container
		// and as a result, invokes the
		// destroy() method
		configurableAP.close();
	}
}
</pre>
</div>

Conclusion

The most crucial component of any Spring application is the use of Spring Beans. The initialization of the Spring Beans specified in the spring bean configuration file is the responsibility of the Spring ApplicationContext.

Spring Context also handles injection dependencies in the bean through setter or constructor methods or spring autowiring.

To validate third-party services or establish database connections, we may wish to initialize resources in the bean classes before making client requests. There are several approaches to implementing post-initialization and pre-destroy methods in a spring bean life cycle using the spring framework.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *