Spring Bean Lifecycle in Java

0
18

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.

[Container Started] → [Bean Instantiated] → [Dependencies injected]→ [Custom init() method]→ [custom utility method]→ [Custom destroy() method]

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() method to run all of 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 understand 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.

// 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");
	

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

<!DOCTYPE>
			
<beans>
	<bean id="cw" class="beans.CodeWorld"
			init-method="init" destroy-method="destroy"/>
	
</beans>

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

//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();
	

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 destroy() 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.

// 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");
	

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

<!DOCTYPE>
			
<beans>
	<bean id="cw" class="beans.CodeWorld"/>
	
</beans>

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

// 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();
	


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.

// 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");
	

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

<!DOCTYPE">
			
<beans>

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

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

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

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

// 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();
	


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.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here