
When the beans get instantiated it is required to perform some initialization to get it to an unstable state. Also, when the bean is no longer required and gets removed from the IoC container some clean-up is required. There are lists of things that take place behind during the time of the initialization of the bean and its destruction. You will declare the bean using <bean> with init method and destroy-method
Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed. Therefore, if we want to execute some code on the bean instantiation and just after closing the spring container, then we can write that code inside the custom init() method and the destroy() method.
1. By XML:
2. By Programmatic Approach:
3. Using Annotation:
Spring Bean Life Cycle – Initialization and Destruction
Bean Life Cycle-Initialisation and Destruction
<bean id = "examp<leBean" class = "examples.ExampleBean" init-method = "init"/> |
<bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/> |
Example
Here is the content of HelloWorld.java file −
package com. example; public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); } public void init(){ System.out.println("Bean is going through init."); } public void destroy() { System.out.println("Bean will destroy now."); } } |
configuration file Beans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "helloWorld" class = "com.example.HelloWorld" init-method = "init" destroy-method = "destroy"> <property name = "message" value = "Hello World!"/> </bean> </beans> |
MainApp.java
package com.example; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); context.destroy(); } } |
//Output
//Output Bean is going through init. Your Message: Hello World! Bean will destroy now. |