Nearby lessons
6 of 35Spring - Bean Lifecycle
- Understand Spring - Bean Lifecycle
- See working code examples
- Learn from common mistakes and Q&A
Learn Spring - Bean Lifecycle step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.
Bean Lifecycle
In spring framework applications, when IOC Container recognizes all the beans definitions
in beans configuration file then IOC Container will execute that bean by using the
following lifecycle actions.
- Bean Class Loading
- Bean Instantiation
- Bean Initialization
- Bean Destruction
- Bean Class Loading:
When IOC Container recognized fully qualified names of the bean classes in beans
configuration file then IOC Container will load the specified bean class byte code to the
memory. To load bean class bytecode to the memory, IOC Container will use the
following method.
public static Class forName(String class_Name)throws ClassNotFoundException
EX: Class c=Class.forName("com.durgasoft.beans.Welcom
eBean");
- Bean Instantiation
In Spring applications, after loading bean class bytecode to the memory, IOC Container
will create object for the bean class.
IN Spring applications we are able to use the following three approaches to create Bean
objects.
1.By using Constructor directly.
2.By Using Static Factory Method
3.By Using Instance Factory Method
- Bean Instantiation through Constructors:
If we want to create bean objects by using constructors then we must provide 0-arg
costructor in bean class irrespective of bean class constructor scopes.
Note: In Bean class , if we provide parameterized constructor then IOC Container will rise
an exception.
EX:
HelloBean.java
pbulic class HelloBean{
public HelloBean(){
System.out.println("Bean Instantiation");
}
public String sayHello(){
System.out.println("Hello User!";
}
}
applicationContext.xml
<beans>
<bean id="hello" class="HelloBean"/>
</beans>
Test.java
class Test{
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean bean=(HelloBean)context.getBean("hello");
System.out.println(bean.sayaHello());
}
}
- Bean Instantiation through Static Factory Method:
In this approach, first we have to define static factory method in Bean class and we have
to configure that static factory method in bean defination in beans configuration file.
EX:
HelloBean.java
public class HelloBean{
public static HelloBean getInstance(){
System.out.println("Static Factory Method");
return new HelloBean();
}
public String sayHello(){
System.out.println("Hello User!";
}
}
applicationContext.xml
<beans>
<bean id="hello" class="HelloBean"
factory-method="getInstance"/>
</beans>
Test.java
class Test{
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean bean=(HelloBean)context.getBean("hello");
System.out.println(bean.sayaHello());
}
}
- Bean Instantiation through INstance Factory Method:
In this approach, we have to define a seperate factory class with instance factory method
and we have to configure factory class as bean in beans configuration file then we have
to configure factory class and factory method in the original bean class definition by using
"factory-bean" and
"factory-method" attributes.
EX:
HelloBeanFactory.java
public class HelloBeanFactory{
public HelloBean getBeanInstance(){
SYstem.out.println("Instance Factory Method");
return new HelloBean();
}
HelloBean.java
public class HelloBean{
public String sayHello(){
System.out.println("Hello User!";
}
}
applicationContext.xml
<beans>
<bean id="hello" class="HelloBean"
factory-method="getBeanInstance"
factory-bean="factory" />
<bean id="factory" class="HelloBeanFactory"/>
</beans>
Test.java
class Test{
public static void main(String[] args){
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean bean=(HelloBean)context.getBean("hello");
System.out.println(bean.sayaHello());
}
}
Bean Initialization and Bean Destruction
As part of Beans lifecycle, IOC Container has to perform Beans initialization after the
Bean Instantiation and IOC Container has to perform Bean destruction after executing the
business logic or at the time of shutdown the IOC Container.
There are three ways to perform Beans initialization and destruction in Spring
Framework.
- By using Custom initialization and destruction methods.
- By using InitializingBean and DesposableBean callback interfaces.
- By using @PostConstruct and @Predestroy annotations
- By using Custom initialization and destruction methods:
In this approach, we have to define user defined initialization and destruction methods
with any name and we have to configure that user defined methods in beans definitions
in beans configuration file by using "init-method" and "destroy-method" attributes in
<bean> tag.
EX:
WelcomeBean.java
package com.durgasoft.beans;
public class WelcomeBean {
public void init(){
System.out.println("User defined init() method");
}
public String sayWelcome(){
return "Welcome To Durga Software Solutions";
}
public void destroy(){
System.out.println("User defined destroy() Method");
}
}
applicationContext.xml
<beans>
| <bean id="wel" | class="com.durgasoft.beans.WelcomeBean" |
|---|
init-method="init" destroy-method="destroy" />
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.WelcomeBean;
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
WelcomeBean bean=(WelcomeBean)context.getBean("wel");
System.out.println(bean.sayWelcome());
context.registerShutdownHook();
}
}
- By using InitializingBean and DesposableBean callback interfaces:
IN Spring framework, InitializingBean is a callback interface , it provides the following
method to execute while performing bean initialization by IOC Container.
public void afterPropertiesSet()throws Exception
Note: This method will be executed by the container after executing all the setXXX()
methods of bean class by ApplicationContext.
IN Spring framework, DisposableBean is a callback interface, it provides the following
method to execute while performing Bean Destruction by IOC Container.
public void destroy()
EX:
WelcomeBean.java
package com.durgasoft.beans;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class WelcomeBean implements InitializingBean,DisposableBean{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
System.out.println("setMessage()");
}
public String sayWelcome(){
return message;
}
@Override
public void afterPropertiesSet() throws Exception {
message="Welcome To Durga Software Solutions";
System.out.println("afterPropertiesSet()");
}
@Override
public void destroy() throws Exception {
System.out.println("destroy()");
}
}
applicationContext.xml
<beans>
<bean id="wel" class="com.durgasoft.beans.WelcomeBean">
<property name="message" value="Welcome To Durgasoft"/>
</bean>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.WelcomeBean;
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
WelcomeBean bean=(WelcomeBean)context.getBean("wel");
System.out.println(bean.sayWelcome());
context.registerShutdownHook();
}
}
- By using @PostConstruct and @Predestroy annotations
@PostConstruct annotation will make a method to execute by the IOC Container while
performing Beans iniitalization.
@Predestroy annotation will make a method to execute by the IOC Container while
performing Bean Destruction.
EX:
Welcome.java
package com.durgasoft.beans;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class WelcomeBean {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
System.out.println("setMessage()");
}
public String sayWelcome(){
return message;
}
@PostConstruct
public void init(){
System.out.println("postConstruct method");
}
@PreDestroy
public void destroy(){
System.out.println("preDestroy method");
}
}
applicationContext.xml
<beans >
<context:annotation-config/>
<bean id="wel" class="com.durgasoft.beans.WelcomeBean">
<property name="message" value="Welcome To Durgasoft"/>
</bean>
</beans>
Note: We need to provide "context" name space along with beans name space in spring
beans configuration file.
Test.java
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
WelcomeBean bean=(WelcomeBean)context.getBean("wel");
System.out.println(bean.sayWelcome());
context.registerShutdownHook();
}
}
Note: IN general, in spring framework applications, we are able to use either of the above
three approaches to perform beans initialization and destruction, we are not using all
three approaches at a time. If we use all the above three approaches in single bean theni
IOC Container will execute the above three approaches provided intialization methods
and destruction methods in the following order.
Initialiazation order:
a) an initialization method marked with @Postconstruct annotation.
b) afterPropertiesSet() method provided by InnitializingBean callback interface.
c) an initialization method configured with "init-method" in <bean> tag in beans
configuration file
Destruction Order
a) A Destruction method marked with @Predestroy annotation
b) destroy() method provided by DisposableBean callback interface.
c) A destruction method configured with "destroy-method" annotation in <bean> tag in
beans configuration file.
Note: If we have same initialization method and destruction method in more than one
bean class in spring application then we are able to provide common init method and
destroy method configuration by using
"default-init-method" attribute and "default-destroy-method" attribute in <beans>
tag[not in <bean> tag] with out providing "init-method" and "destroy-method" attributes
in <bean> tag at each and every bean configuration.
EX:
Welcome.java
public class Welcome {
public void init(){
System.out.println("init()-Welcome");
}
public void destroy(){
System.out.println("destroy()-Welcome");
}
}
Hello.java
public class Hello{
public void init(){
System.out.println("init()-Hello");
}
public void destroy(){
System.out.println("destroy()-Hello");
}
}
spring_beans_config.xml
<beans default-init-method="init" default-destroy-method="destroy">
<bean id="welcome" class="com.durgasoft.beans.Welcome"/>
<bean id="hello" class="com.durgasoft.beans.Hello"/>
</beans>
Test.java
public class Test{
public static void main(String[] args){
AbstractApplicationContext context=new ClassPathXmlApplicationContext("
/com/durgasoft/cfgs/spring_beans_config.xml");
Welcome bean1=(Welcome)context.getBean("welcome");
Hello bean2=(Hello)context.getBean("hello");
context.registerShutdownHook();
}
}
- Beans Inheritance:
In general, in Spring framework, we are able to provide more and more no of
configuration details in beans definitions under beans configuration file like properties
configurations, dependency injection related configurations, initialization destruction
methods configurations,.......
In the above context, we are able to reuse one bean configuration details in another bean
configurations like normal java classes inheritance inorder to improve reusability and
inorder to reduce no of configurations in spring configuration file by declaring parent and
chaild beans configurations.
To declare a particular bean configuration as parent to the present bean configuration
then we have to use "parent" attribute in "<bean>" tag in beans configuration file, where
"parent" attribute will take identity of the respective bean definition.
EX:
WishBean.java
package com.durgasoft.beans;
public class WishBean {
private String wish_Message;
private String name;
public void init(){
System.out.println("WishBean Initialization");
}
public void destroy(){
System.out.println("WishBean Destruction");
}
setXXX()
getXXX()
}
HelloBean.java
package com.durgasoft.beans;
public class HelloBean {
private String wish_Message;
private String name;
public void init(){
System.out.println("HelloBean Initialization");
}
public void destroy(){
System.out.println("HelloBean Destruction");
}
setXXX()
getXXX()
public String sayHello(){
return wish_Message+name;
}
}
WelcomeBean.java
package com.durgasoft.beans;
public class WelcomeBean {
private String wish_Message;
private String name;
public void init(){
System.out.println("WelcomeBean Initialization");
}
public void destroy(){
System.out.println("WelcomeBean Destruction");
}
setXXX()
getXXX()
public String sayWelcome(){
return wish_Message+name;
}
}
spring_beans_config.xml
<beans>
<bean id="wishBean" class="com.durgasoft.beans.WishBean" init-method="init"
destroy-method="destroy">
<property name="wish_Message" value="Durga Software Solutions"/>
<property name="name" value="Anil"/>
</bean>
<bean id="helloBean" class="com.durgasoft.beans.HelloBean" parent="wishBean">
<property name="wish_Message" value="Hello "/>
</bean>
<bean id="welcomeBean" class="com.durgasoft.beans.WelcomeBean"
parent="wishBean">
<property name="wish_Message" value="Welcome "/>
</bean>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.HelloBean;
import com.durgasoft.beans.WelcomeBean;
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("/com/durgasoft/cfgs/ spring_beans_config.xml");
HelloBean hello=(HelloBean)context.getBean("helloBean");
System.out.println(hello.sayHello());
System.out.println();
WelcomeBean welcome=(WelcomeBean)context.getBean("welcomeBean");
System.out.println(welcome.sayWelcome());
context.registerShutdownHook();
}
}
In the above Beans Inheritance, it is possible to declare parent bean definition as a
template, that is, a set of configurations which we want to apply to chaild definintions,
not to have its own bean class and not to apply to its own bean class.
To declare a bean definition as template we have to use "abstract" attribute with "true"
value in <bean> tag , in this context, it is not required to use "class" attribute in bean tag.
EX:
<beans>
<bean id="wishBean" abstract="true" .... >
</bean>
<bean id="helloBean" class="HelloBean" parent="wishBean">
</bean>
<bean id="welBean" class="WelcomeBean" parent="wishBean">
</bean>
</beans>
Example:
WishBean.java
package com.durgasoft.beans;
public class WishBean {
private String wish_Message;
private String name;
public void init(){
System.out.println("WishBean Initialization");
}
public void destroy(){
System.out.println("WishBean Destruction");
}
public String getWish_Message() {
return wish_Message;
}
public void setWish_Message(String wish_Message) {
this.wish_Message = wish_Message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
HelloBean.java
package com.durgasoft.beans;
public class HelloBean {
private String wish_Message;
private String name;
public void init(){
System.out.println("HelloBean Initialization");
}
public void destroy(){
System.out.println("HelloBean Destruction");
}
public String getWish_Message() {
return wish_Message;
}
public void setWish_Message(String wish_Message) {
this.wish_Message = wish_Message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String sayHello(){
return wish_Message+name;
}
}
WelcomeBean.java
package com.durgasoft.beans;
public class WelcomeBean {
private String wish_Message;
private String name;
public void init(){
System.out.println("WelcomeBean Initialization");
}
public void destroy(){
System.out.println("WelcomeBean Destruction");
}
public String getWish_Message() {
return wish_Message;
}
public void setWish_Message(String wish_Message) {
this.wish_Message = wish_Message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String sayWelcome(){
return wish_Message+name;
}
}
Test.java
package com.durgasoft.test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.HelloBean;
import com.durgasoft.beans.WelcomeBean;
import com.durgasoft.beans.WishBean;
public class Test {
public static void main(String[] args)throws Exception {
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
//WishBean wish = (WishBean)context.getBean("wishBean");---> Exception
//System.out.println(wish);
HelloBean hello=(HelloBean)context.getBean("helloBean");
System.out.println(hello.sayHello());
System.out.println();
WelcomeBean welcome=(WelcomeBean)context.getBean("welcomeBean");
System.out.println(welcome.sayWelcome());
context.registerShutdownHook();
}
}
applicationContext.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="wishBean" abstract="true" init-method="init" destroy-method="destroy">
<property name="wish_Message" value="Durga Software Solutions"/>
<property name="name" value="Anil"/>
</bean>
<bean id="helloBean" class="com.durgasoft.beans.HelloBean" parent="wishBean">
<property name="wish_Message" value="Hello "/>
</bean>
<bean id="welcomeBean" class="com.durgasoft.beans.WelcomeBean"
parent="wishBean">
<property name="wish_Message" value="Welcome "/>
</bean>
</beans>
- Key ideas of Spring - Bean Lifecycle explained simply
- Ready-to-use code examples
- Exam-style questions at the end